对NGINX中的重写规则感到困惑



我正在移动一个项目,将Docker与Nginx一起使用,后者以前使用过Apache。这是一个简单的PHP项目,但我无法像在Apache上那样进行重写。旧的.htaccess是简单的;

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L,QSA]

它使用page参数将所有页面请求重定向到index.php文件,然后使用自定义PageControllerindex.php中解析该文件。然而,我无法用Nginx重写来实现这一点,这让我很困惑。

目标是将类似index.php?page=forgot_password的URL重写为forgot_password

我当前的nginx.conf是

server {
listen 80 default_server;
root /app/app;
index index.php index.html index.htm;
location ~ .php$ {
fastcgi_pass php:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

这显然不起作用,因为没有重写规则。

我尝试了一些其他配置,例如Symfony文档中的Nginx配置,它将所有页面重定向到index.php,但不提供page查询参数。

我试过其他配置,比如

location ~ .php$ {
fastcgi_pass php:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location / {
if (!-e $request_filename){
rewrite ^(.+)$ /index.php?page=$1 break;
}
}

这导致Firefox提示我下载前面的_ password文件。

我还做过其他尝试(遗憾的是,我记不清了(,它们似乎确实按照我想要的方式工作,但导致JS、CSS和其他资源不再工作。

我该怎么做?我觉得我错过了一些简单的东西。

对于nginx配置,或者重写索引如下:

location / {
if (!-e $request_filename){
rewrite ^(.+)$ /index.php?page=$1 break;
}
}

或者:

server {
server_name yourdomain.com;
location ~ "^/(.+)$" {
try_files $uri $uri/ /index.php?page=$1;
}
}

最新更新