301使用Nginx重定向

问题描述

我从以下表格移走了我的网站网址:

https://example.com/category/sub-category/post-url
https://example.com/category/post-url

此表单:

https://example.com/post-url

我想设置nginx重定向,以免丢失访问旧URL的访问者。

我找到了我需要使用的正则表达式,它就是([^\/]+$)(在最后一个斜杠之后取所有文本)。但是我该如何设置它与nginx一起使用?

解决方法

在服务器块条目中,您需要添加:

server {
  ...
  # Your match:
  rewrite ^\/[^\/]+\/(.*) /$1 redirect;
  # Probably a better regex (I cannot test)
  # rewrite ^\/.*\/([^\/.]*)$ /$1 redirect;
  ...
}

redirect的状态为302,如果您想进行永久移动(dangerous),请使用permanent(301)。正则表达式通常与您的正则表达式匹配(尽管实际上,我认为它不会满足您的要求。.您需要它来贪婪地匹配除最后一个斜杠以外的所有内容,但我添加了一个替代方案,您可能希望通过{ {3}})和分组匹配(.*),然后在重定向中将其称为$1

css / js / jpg / gif / png的更新

这很容易出错,但是由于您的发布网址似乎未包含点(.),因此我们可以过滤组匹配项以排除点,从而导致以匹配结尾的file.ext结尾的URL。

^\/.*\/([^\/.]*)$上使用Nginx tester,我们可以找到合理的准确性(没有您所拥有物品的实际详细信息):

匹配:

/category/sub-category/post-url
/category/post-url

不匹配:

/images/blog.jpg #no match
/css/main.css #no match
/js/app.js
/favicon.ico

但是,如果您的发布网址可以包含点,则此方法将无效。此外,如果您有任何不包含点的静态文件-这将不起作用(您必须在正则表达式中更详细地说明不匹配/不匹配的网址)

,

最简单的方法是.htaccess文件。只需创建一个名为.htaccess的文本文件(末尾没有.txt!)。与以下行:

Redirect /olddirectory/oldfile.html http://example.com/newdirectory/newfile.html

将其导入到nginx.config

否则:

server {
    listen 80;
    listen 443 ssl;
    server_name old url;
    return 301 $scheme://new url;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...