Nginx提供了强大的URL重写功能,主要通过rewrite指令和location块来实现基于请求URI的请求重写。以下是详细的配置方法和示例:
rewrite regex replacement [flag];
regex: 正则表达式匹配原始URIreplacement: 替换后的URIflag: 可选参数,控制重写行为last: 停止处理当前rewrite指令集,并用重写后的URI重新搜索locationbreak: 停止处理当前rewrite指令集redirect: 返回302临时重定向permanent: 返回301永久重定向location /old-path/ {
rewrite ^/old-path/(.*)$ /new-path/$1 last;
}
if ($request_uri ~* "^/product/([0-9]+)") {
rewrite ^/product/([0-9]+)$ /products?id=$1? last;
}
rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
# 确保URI以斜杠结尾
rewrite ^([^.]*[^/])$ $1/ permanent;
# 去除尾部斜杠
rewrite ^/(.*)/$ /$1 permanent;
rewrite ^/category/(.+)/subcategory/(.+)$ /products?cat=$1&subcat=$2? last;
location /old-page.html {
rewrite ^/old-page.html$ /new-page.html permanent;
}
last或breakpermanent或redirectrewrite_log on;
error_log /var/log/nginx/error.log notice;
return指令测试模式匹配:location /test-rewrite {
return 200 "Matched: $request_uri";
}
通过合理配置这些重写规则,你可以实现复杂的URL转换逻辑,同时保持网站的SEO友好性和用户体验。