在Nginx配置中,可以使用rewrite指令來實現URL重寫。以下是一個簡單的示例,說明如何使用rewrite指令將請求從一個URL重定向到另一個URL:
打開Nginx配置文件。通常位于/etc/nginx/nginx.conf或/etc/nginx/sites-available/your_domain.conf。
在server塊中,找到location塊,或者創建一個新的location塊。
在location塊中,添加rewrite指令。例如,將所有以/old-url開頭的請求重定向到/new-url:
location /old-url {
rewrite ^/old-url(.*)$ /new-url$1 last;
}
這里的正則表達式^/old-url(.*)$匹配以/old-url開頭的所有請求。$1表示捕獲的第一個括號內的內容(即. *)。last標志表示完成重寫并停止處理其他重寫規則。
server {
listen 80;
server_name your_domain.com www.your_domain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name your_domain.com www.your_domain.com;
# SSL證書和密鑰配置
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
# 其他配置...
}
sudo nginx -t # 檢查配置文件語法是否正確
sudo nginx -s reload # 重新加載配置文件
現在,當用戶訪問以/old-url開頭的URL時,Nginx會將請求重定向到/new-url。