![](https://www.alaica.com/wp-content/uploads/linux-24.gif)
我已将域名从 long-domain-name-example.com 更改为 example.com,它更短且易于记住。如何在类 Unix 操作系统上运行的 nginx Web 服务器下将旧域重定向到带有“HTTP/1.1 301 Moved Permanently”状态代码的新域?
教程详情 | |
---|---|
难度级别 | 中间的 |
根权限 | 是的 |
要求 | nginx |
美东时间。阅读时间 | 3分钟 |
Nginx Web 服务器带有名为 HttpRewriteModule 的模块。使用此模块可以使用正则表达式 (PCRE) 更改 URI,并根据变量重定向和选择配置。您所要做的就是捕获旧域并重定向到新域。编辑/usr/local/nginx/conf/nginx.conf或/etc/nginx/nginx.conf运行:在声明 server_name 后
# vi /usr/local/nginx/conf/nginx.conf
在块中附加以下行:server{ ... }
重写 ^ $scheme://www.example.com 永久;
在这种情况下,对 uri 的所有请求,例如 long-domain-name-example.com、long-domain-name-example.com/file.html、long-domain-name-example.com/folder/file2.php、 long-domain-name-example.com/cgi-bin/register.cgi?action=1 全部重定向到 www.example.com,代码为 301。但是,您可能也想复制并传递 URL,请尝试:
重写 ^ $scheme://www.example.com$request_uri 永久;
该$request_uri变量等于从客户端接收到的原始请求 URI(包括参数)。换句话说,重定向 url 如下,带有 301 状态代码:
http://long-domain-name-example.com 到 http://www.example.com http://long-domain-name-example.com/file.html 到 http://www.example.com/file.html http://long-domain-name-example.com/cgi-bin/register.cgi?action=1 到 http://www.example.com/cgi-bin/register.cgi?action=1 http://long-domain-name-example.com/static/js/lib.js?v=2 到 http://www.example.com/static/js/lib.js?v=2
示例代码块:
### 使用301 ###将 beta.example.com$URI 重定向到 www.example.com$URI 服务器{ 监听 75.126.153.206: 80 ; 服务器名称 beta.example.com; 根/usr/local/nginx/html; 索引index.html; 重写 ^ $scheme://www.example.com$request_uri 永久; # .... }
保存并关闭文件。重新加载 nginx Web 服务器,运行:
# /usr/local/nginx/sbin/nginx -s reload
重定向与永久标志
带有 http 状态代码 301 的标志permanent重定向 URL。这意味着页面已永久移动到新位置。这段代码是搜索引擎巨头Google推荐的:
301 重定向在以下情况下特别有用:
- 您已将网站移至新域,并且希望尽可能无缝地进行转换。
- 人们通过几个不同的 URL 访问您的网站。例如,如果您的主页可以通过多种方式访问 - 例如,http://example.com/home、http://home.example.com 或 http://www.example.com - 则可以最好选择这些 URL 之一作为您的首选(规范)目标,并使用 301 重定向将流量从其他 URL 发送到您的首选 URL。您还可以使用网站管理员工具来设置您的首选域。
- 您正在合并两个网站,并希望确保过时 URL 的链接被重定向到正确的页面。
该redirect标志返回带有 http 状态代码 302 的临时重定向。这意味着页面已暂时移动到新位置。不建议使用此代码进行域更改。
参考
- 来自 nginx wiki 的HttpRewriteModule模块文档。