Nginx作为高性能Web服务器,其伪静态规则(又称URL重写)的核心机制是通过rewrite指令和正则表达式,将动态URL转换为对用户和搜索引擎更友好的静态形式,下面从基础语法到实际案例展开说明。
Nginx伪静态规则的基本位置
规则通常写在server块或location块中,对于大多数站点,推荐放在server块下,避免与location内的其他逻辑冲突。
server { listen 80; server_name example.com; # 伪静态规则写在此处}核心指令:rewrite 与 try_files
rewrite指令
语法:rewrite 正则表达式 替换地址 [标志位];
常用标志位:
last:停止当前location处理,重启新一轮规则匹配。 break:停止当前location处理,不再匹配后续规则。 redirect:返回302临时重定向。 permanent:返回301永久重定向。示例:将/article?id=123重写为/article-123.htmlrewrite ^/article-(\d+)\.html$ /article?id=$1 last;
try_files指令
常用于单入口框架(如ThinkPHP、WordPress),按顺序检查文件是否存在。try_files $uri $uri/ /index.php?$query_string;
表示:先尝试请求静态文件,再尝试目录,最后将请求交给index.php处理。
典型场景的规则写法
场景1:HTML伪静态
动态URL:/product.php?id=10
伪静态形式:/product-10.html
rewrite ^/product-(\d+)\.html$ /product.php?id=$1 last;
场景2:目录层级伪静态
动态URL:/index.php?cat=news&id=5
伪静态形式:/news/5.html
rewrite ^/([a-z]+)/(\d+)\.html$ /index.php?cat=$1&id=$2 last;
场景3:WordPress常规伪静态
location / { try_files $uri $uri/ /index.php?$args;}场景4:Discuz论坛伪静态
rewrite ^(.*)/topic-(.+)\.html$ $1/portal.php?mod=topic&topic=$2 last;
调试与常见错误
nginx -t语法是否正确,并确认server块中已开启rewrite功能(默认开启)。 last或break防止无限循环。rewrite ^/index\.php$ /index.php?page=home last;会陷入死循环,需改用 if条件判断。 if检测$request_uri。进阶技巧
if条件做精细控制: if (!-e $request_filename) { rewrite ^(.*)$ /index.php last;}map模块批量映射规则(减少重复正则)。 rewrite放在server块而非location块,避免重复匹配。掌握以上核心思路,即可根据业务需求编写绝大多数Nginx伪静态规则,实际部署时,建议先用curl或浏览器开发者工具验证重写结果,确保路径正确。
相关文章:
0.5929s , 5865.546875 kb Copyright 2023 Powered by 南宁SEO关键词排名推广sitemap