Nginx實現(xiàn)前端重定向的三種方法介紹
需求:
http://127.0.0.1/test-chat/orig_docs/80a4e16a-6945-4fa0-bc8a-2b9c9c6eacb7
使用 nginx 轉(zhuǎn)為下面的請求
http://127.0.0.1/orig_docs/80a4e16a-6945-4fa0-bc8a-2b9c9c6eacb7
可以使用 nginx 的rewrite或location指令來實現(xiàn)這個 URL 轉(zhuǎn)換。以下是幾種配置方式:

方法 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;
# 代理到實際服務(wù)
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;
# 重寫規(guī)則:移除test-chat前綴
rewrite ^/test-chat/orig_docs/(.*)$ /orig_docs/$1 permanent;
# 處理/orig_docs請求
location /orig_docs/ {
# 這里配置您的后端服務(wù)
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;
# 可選:設(shè)置超時時間
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# 其他location配置...
location / {
# 默認(rèn)處理
root /usr/share/nginx/html;
index index.html;
}
}
配置說明
permanent (301 重定向):瀏覽器會記住重定向,適合永久性 URL 變更
redirect (302 重定向):臨時重定向,每次都會請求原 URL
break:在 server 內(nèi)部重寫,不對外部重定向
測試配置
# 檢查nginx配置語法 nginx -t # 重新加載配置 nginx -s reload
選擇哪種方法取決于您的具體需求:
- 如果希望用戶瀏覽器地址欄顯示新的 URL,使用
permanent或redirect - 如果只是內(nèi)部重寫,使用
break - 如果需要代理到其他服務(wù),使用方法 2 的代理配置
到此這篇關(guān)于Nginx實現(xiàn)前端重定向的三種方法介紹的文章就介紹到這了,更多相關(guān)Nginx前端重定向內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nginx實現(xiàn)根據(jù)URL轉(zhuǎn)發(fā)請求的實戰(zhàn)經(jīng)歷
這篇文章主要給大家介紹了一次關(guān)于nginx實現(xiàn)根據(jù)URL轉(zhuǎn)發(fā)請求的實戰(zhàn)經(jīng)歷,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用nginx具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Nginx搭配cpolar實現(xiàn)遠(yuǎn)程開發(fā)無縫協(xié)作全過程
Nginx是一款高性能的本地Web服務(wù)器,以其卓越的穩(wěn)定性和靈活的配置能力,成為開發(fā)者搭建本地服務(wù)的首選工具,本文將介紹如何利用 Ubuntu操作系統(tǒng)、Docker容器技術(shù)以及cpolar內(nèi)網(wǎng)穿透工具來實現(xiàn)公網(wǎng)遠(yuǎn)程訪問本地Nginx服務(wù)器的具體操作流程,需要的朋友可以參考下2026-01-01

