【问题标题】:Rewrite all requests to PHP script on Nginx在 Nginx 上重写所有对 PHP 脚本的请求
【发布时间】:2016-12-18 05:46:25
【问题描述】:

我是 Nginx 的新手,对于我的项目,我需要将所有请求重写为 index.php,它是请求处理程序。 我在 Apache 中使用 .htaccess 文件完成了这项工作,但现在我想让它也与 Nginx 兼容。我知道在 Nginx 上不存在 .htaccess 文件,所以我必须在 /etc/nginx/sites-available/default 中编辑虚拟主机文件,但我不知道哪个是 Nginx 等效于我的旧 Apache 规则。 这是我的旧 .htaccess 文件的内容:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !/index\.php
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([^?]*)$ /index.php [QSA,NS,L]

在 Apache 上,所有请求都被重写为 index.php,无论这些是 PHP 脚本、静态文件还是不存在的文件(在我的项目中还有一些虚拟路径,如 /::API/ 或 /::ADMIN / 和根快捷方式 /~/),我怎样才能用 Nginx 做到这一点?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite nginx


    【解决方案1】:

    nginx 文档列出了重写指令:http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

    简单的答案是这样的:

    location / {
        rewrite ^(.*)$ /index.php?$1 last;
    }
    

    编辑添加 ?$1 位。谢谢,@bob0t

    【讨论】:

    • 你忘记了 QSA 标志:这更像是/index.php$query_string
    • 我的文件中有这个:server { location / { rewrite ^(.*)$ /index.php$query_string last; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php7.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; } } 但我得到了 502:PHP 脚本上的网关错误和虚拟路径上的 404(不存在的文件),我错了吗?
    • 检查我的编辑。 Bob0t 说的是结果,而不是要做出的改变。
    • 我已经完成了编辑,所以现在块是:location / { rewrite ^(.*)$ /index.php?$1 last; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php7.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; } 但仍然是同样的错误
    • 谢谢,我已经检查了问题,我已经理解了错误,这里是更正的配置块,也许对其他人也有用:location / { rewrite ^(.*)$ /index.php?$1 last; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME /[PATH TO WEBSITE]/index.php; }
    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多