Nginx实现前端重定向的三种方法介绍
作者:檀越@新空间
这篇文章主要为大家详细介绍了Nginx实现前端重定向的三种方法,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下
需求:
http://127.0.0.1/test-chat/orig_docs/80a4e16a-6945-4fa0-bc8a-2b9c9c6eacb7
使用 nginx 转为下面的请求
http://127.0.0.1/orig_docs/80a4e16a-6945-4fa0-bc8a-2b9c9c6eacb7
可以使用 nginx 的rewrite或location指令来实现这个 URL 转换。以下是几种配置方式:

方法 1:使用 rewrite 指令
server {
listen 80;
server_name 127.0.0.1;
# 方法1.1:在server级别重写
rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent;
# 或者方法1.2:在location中重写
location /test-chat/orig_docs/ {
rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent;
}
}
方法 2:使用 location 代理
server {
listen 80;
server_name 127.0.0.1;
location /test-chat/orig_docs/ {
# 移除test-chat前缀
rewrite ^/test-chat(/orig_docs/.*)$ $1 break;
# 代理到实际服务
proxy_pass http://your_backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /orig_docs/ {
# 处理原始/orig_docs请求
proxy_pass http://your_backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
方法 3:精确的路径重写
server {
listen 80;
server_name 127.0.0.1;
location ~ ^/test-chat/orig_docs/(.+)$ {
return 301 /orig_docs/$1;
}
}
完整的 nginx 配置示例
server {
listen 80;
server_name 127.0.0.1;
# 访问日志
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# 重写规则:移除test-chat前缀
rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent;
# 处理/orig_docs请求
location /orig_docs/ {
# 这里配置您的后端服务
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 可选:设置超时时间
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# 其他location配置...
location / {
# 默认处理
root /usr/share/nginx/html;
index index.html;
}
}
配置说明
permanent (301 重定向):浏览器会记住重定向,适合永久性 URL 变更
redirect (302 重定向):临时重定向,每次都会请求原 URL
break:在 server 内部重写,不对外部重定向
测试配置
# 检查nginx配置语法 nginx -t # 重新加载配置 nginx -s reload
选择哪种方法取决于您的具体需求:
- 如果希望用户浏览器地址栏显示新的 URL,使用
permanent或redirect - 如果只是内部重写,使用
break - 如果需要代理到其他服务,使用方法 2 的代理配置
到此这篇关于Nginx实现前端重定向的三种方法介绍的文章就介绍到这了,更多相关Nginx前端重定向内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
