首页 > 解决方案 > 没有 php 扩展和漂亮的 url nginx 配置替代

问题描述

我刚刚将我的代码从 apache 迁移到 nginx 服务器。

我的 apache .htaccess 的替代 nginx 配置是什么。

我使用的是删除 .php 扩展名和漂亮的 url 重写的规则。

RewriteEngine On

#remove .php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#for pretty url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ index.php?url=$1 [NC,L]

标签: .htaccessnginxnginx-config

解决方案


试试这个

map $uri $pretty_url {
    ~/(.*)$    $1;
}

server {

    ...

    location / {
        index index.php; # replace this to 'index index.php index.html index.htm;' if needed
        try_files $uri $uri/ @extensionless-php;
    }

    location ~ \.php$ {
        # default PHP-FPM handler here
        ...
    }

    location @extensionless-php {
        if ( -f $document_root$uri.php ) {
            rewrite ^ $uri.php last;
        }
        rewrite ^ /index.php?url=$pretty_url last;
    }

}

推荐阅读