【问题标题】:Redirect an old php file to a new URL using Nginx使用 Nginx 将旧的 php 文件重定向到新的 URL
【发布时间】:2013-05-11 15:06:21
【问题描述】:

我有一个网址与 PHP 文件对应的网站:

www.mysite.com/cat.php?id=stuff

这些 PHP 文件不存在了,我该如何做一个 301 重定向(出于 SEO 原因)到新 URL:

 www.mysite.com/stuff

我试过了

 rewrite  ^/cat\.php\?id=stuff  http://www.mysite.com/stuff? permanent;

但它不起作用,我得到一个“没有指定输入文件”。

感谢您的帮助!

编辑:

更多关于我的配置(网站由 Wordpress 提供支持):

    index index.php;
    root /var/www/mydirectory;

    location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

【问题讨论】:

标签: regex redirect nginx


【解决方案1】:

问题是您在重写目录的末尾添加了?,因此 nginx 告诉 PHP 提供不存在的 http://yourdomain.com/stuff?/index.php

假设 mysites.com 是一个错字并且您正在重定向到同一个域,试试这个:

rewrite  ^/cat\.php\?id=(.*)$    /$1/    permanent;

同时使用rewritetry_files 有很多问题,我有一个使用这些的工作配置,例如:

我认为规则是你的rewrite 规则必须在try_files 之前,所以试试这个:

index index.php;
root /var/www/mydirectory;

location = / {
    rewrite  ^/cat\.php\?id=(.*)$    /$1/    permanent;
}

location ^(.*)$ {
    try_files $uri $uri/ /index.php?$1;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

【讨论】:

  • 这个解决方案有效吗?它应该将您传递给id 的任何内容设置为文件夹,以便http://domain.com/cat.php?id=xyz 重定向到http://domain.com/xyz
  • 即使转义正确也不起作用。我仍然得到“没有指定输入文件”
  • 未指定输入文件意味着 nginx 正在将不存在的脚本 URI 传递给 php-fpm。 nginx 在从 php 请求之前不会检查脚本是否存在。直接去http://yourdomain.com/stuff/ 有效吗?
  • 我写道:重写 ^/cat\.php\?id=(.*)$ /stuff Permanent;但是当 url /stuff 确实有效时,我仍然遇到同样的错误
  • @JuCachalot - 更新了答案,没有注意到你也在使用try_files。这两条规则玩得不好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 2017-12-22
  • 1970-01-01
相关资源
最近更新 更多