【问题标题】:Nginx rewrite rules are not working as expectedNginx 重写规则未按预期工作
【发布时间】:2020-01-12 14:32:51
【问题描述】:

我有一个网站 https://dev.mywebsite.com/index.php?album=portraits 它根据 POST 值动态显示相册。

我想将此 URL 重写为: https://dev.mywebsite.com/portraits

但是我的 Nginx 重写规则不起作用。当我输入https://dev.mywebsite.com/index.php?album=portraits 时什么都没有发生。并且输入https://dev.mywebsite.com/portraits时找不到页面。

我不知道我做错了什么。

这是我目前正在尝试使用的代码:

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

我也试过这个:

location = /portraits { 
        rewrite ^/portraits?$ /index.php?album=portraits break; 
}

还有这个:

location = /album { 
        rewrite ^album/([a-z]+)/?$ album.php?album=$1 break; 
}

这是我正在使用的整个 nginx 站点配置文件:

server {
        listen 80 default_server;
        listen 443 ssl;                                         
        root /config/www;
        index index.php index.htm index.html;
        server_name dev.mywebsite.com;

        ssl_certificate /config/keys/cert.crt;
        ssl_certificate_key /config/keys/cert.key;

        client_max_body_size 0;

        location / {
                try_files $uri $uri/ /index.html /index.php?$args =404;
        }
    location / {
                rewrite ^/(.*)$ /album.php?album=$1 last;
        }

    location ~ \.php$ {
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
                # With php5-cgi alone:
                fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                #fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include /etc/nginx/fastcgi_params;

        }
}

【问题讨论】:

  • 您不能有两个 location / 块。使用nginx -t 测试您的配置文件。 php文件叫album.php还是index.php?
  • 谢谢我不知道我不能有两个。我使用的文件是 index.php。但我也尝试使用album.php 以另一种方式设置它,因为没有任何效果。

标签: php nginx url post


【解决方案1】:

如果你真的拥有的文件是index.php,那么你可以重写(无需任何额外的location):

rewrite ^/portraits$ /index.php?album=portraits last;

当然保留location ~ \.php$ { :)

【讨论】:

  • 感谢您的成功!我也将portraits 分别更改为([a-z]+) 和$1,所以它适用于我的所有专辑。
猜你喜欢
  • 2013-08-11
  • 2016-06-10
  • 1970-01-01
  • 2015-02-03
  • 2018-08-12
  • 2013-07-24
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多