【问题标题】:How to redirect all request to index.php even with .php in the url即使 url 中有 .php,如何将所有请求重定向到 index.php
【发布时间】:2022-05-06 07:57:40
【问题描述】:

我有这个 nginx 虚拟主机配置:

server {
        listen 8081;
        server_name blocked_server;
        root /home/gian/blocked_server;
        access_log off;
        error_log off;
        index index.php index.html index.htm index.nginx-debian.html;

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

        location ~ / {
                try_files $uri $uri /index.php;
        }
}

它将所有 url 重定向到 index.php,除非 url 以 .php 扩展名结尾。

例如这有效: http://localhost/somethingthatdontexist

但这会返回 404 并且不会重定向到 index.php http://localhost/somethingthatdontexist.php

如何将不存在的带有 .php 扩展名的 url 重定向到 index.php?

【问题讨论】:

  • 尝试将try_files $uri /index.php; 添加到您的location ~ \.php$ 块中。
  • 我尝试将其添加到 location ~\.php$ 块中,但由于此错误,我无法重新加载 nginx:nginx: [emerg] "try_files" directive is duplicate in /etc/nginx/snippets/fastcgi-php.conf:5
  • 检查snippets/fastcgi-php.conf 文件的内容。您可以更改其中的try_files 语句,或者将文件的内容粘贴到location 块中,以便在那里进行编辑。

标签: nginx


【解决方案1】:

我已经解决了这个问题。 首先你应该注释掉这一行或从snippets/fastcgi-php.conf文件中删除这一行

try_files $fastcgi_script_name =404;

然后在您的虚拟主机配置中将try_files $uri $uri /index.php; 放在include snippets/fastcgi-php.conf; 之前的location ~\.php$ 块上。

location ~\.php$ 块应如下所示:

location ~ \.php$ {
    try_files $uri $uri /index.php;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

这应该可以解决问题。

【讨论】:

  • 或者您也可以将错误404页面设置为index.php。
【解决方案2】:

我认为@Richard Smith (https://stackoverflow.com/users/4862445/richard-smith) 对原始问题提出的 cmets 非常重要,应该作为答案添加。

将 try_files 添加到 .php 位置是答案,但它会导致错误,因为该选项已在包含的 sn-p 中设置。

只需编辑 /etc/nginx/sn-ps/fastcgi-php.conf 并将 try_files 选项更改为您想要的结果即可解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2015-04-10
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    相关资源
    最近更新 更多