// 来源:https://www.nzw6.com
《nginx配置redirect跳转页面》
在Nginx中实现页面重定向(redirect)是一个常见的需求,它能够帮助我们轻松地将用户从一个URL导向到另一个URL。最直接的解决方案是通过修改Nginx的配置文件,在其中添加特定的指令来完成这一操作。
一、使用return指令
这是非常简洁的一种方式。假设我们要将对http://old.example.com
的请求重定向到http://new.example.com
。
nginx
server {
listen 80;
server_name old.example.com;</p>
<pre><code>location / {
return 301 http://new.example.com$request_uri;
}
}
``
301
这里的表示永久重定向,告诉浏览器和搜索引擎这个资源已经永久移动到新的地址了,这有助于搜索引擎优化(SEO)。而
$request_uri`变量用于保留原始请求的URI部分,确保原路径和参数等信息能够正确传递到新的地址。
二、使用rewrite指令
如果需要更灵活地根据某些规则进行重定向,rewrite
指令会很有用。例如,当访问/oldpath
时,重定向到/newpath
。
```nginx
server {
listen 80;
server_name example.com;
location /oldpath {
rewrite ^/oldpath(.*)$ /newpath$1 permanent;
}
}
这里^/oldpath(.*)$
是正则表达式匹配模式,用来匹配以/oldpath
开头的URL,$1
表示个括号中的捕获组,即匹配到的内容。permanent
也表示永久重定向,如果不希望是永久重定向,可以将其改为redirect
表示临时重定向。
三、基于条件判断的重定向
有时候可能需要根据一些条件来进行重定向操作,比如根据请求的来源IP地址或者请求头等。下面是一个根据请求头User - Agent来重定向移动设备用户的例子。
nginx
server {
listen 80;
server_name example.com;</p>
<pre><code>set $mobile_redirect "";
if ($http_user_agent ~* "(android|bbd+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
set $mobile_redirect "true";
}
if ($http_user_agent ~* "htc|samsung|sch-|sonyericsson|nokia|sagem|sanyo|sec-|sie-|motorola") {
set $mobile_redirect "true";
}
if ($mobile_redirect = "true") {
rewrite ^/(.*)$ http://m.example.com/$1 redirect;
}
}
以上就是在Nginx中配置redirect跳转页面的方法,不同的场景可以根据实际需求选择合适的方式。在修改Nginx配置后,别忘了检查配置是否正确(如使用nginx -t
命令),然后重新加载或重启Nginx使配置生效。