在 Web 开发和服务器管理中,Nginx 的 rewrite
指令是一个非常实用的工具。它允许我们根据特定规则修改请求的 URL,实现 URL 重写和重定向等功能。
1. rewrite
指令的基本语法
rewrite
指令的基本语法如下:
rewrite regex replacement [flag];
- regex:用于匹配请求 URI 的正则表达式。
- replacement:匹配成功后,将 URI 替换为该字符串。
- flag:可选参数,用于控制重写后的行为,常见的有:
- last:表示完成重写后,重新在 server 块中进行 location 匹配。
- break:表示停止执行当前 location 块内的后续 rewrite 指令。
- redirect:返回 302 临时重定向,浏览器地址栏会显示新的 URL。
- permanent:返回 301 永久重定向,浏览器地址栏也会显示新的 URL。
2. 实际应用示例
示例 1:将动态 URL 重写为伪静态 URL
假设我们有一个动态 URL,如 http://example.com/article.php?id=123
,希望将其重写为伪静态 URL http://example.com/article/123
,以提高 SEO 友好性。
location /article/ {
rewrite ^/article/([0-9]+)$ /article.php?id=$1 last;
}
在这个配置中,rewrite
指令将 /article/123
重写为 /article.php?id=123
,并使用 last
标志表示重写后重新在 server 块中进行 location 匹配。
示例 2:根据请求的域名进行重定向
如果我们希望将访问 http://old-domain.com
的请求重定向到 http://new-domain.com
,可以使用以下配置:
server {
listen 80;
server_name old-domain.com;
rewrite ^(.*)$ http://new-domain.com$1 permanent;
}
这里,rewrite
指令将所有访问 old-domain.com
的请求永久重定向到 new-domain.com
,并使用 permanent
标志表示永久重定向。
示例 3:阻止对特定文件的访问
有时,我们需要阻止对某些敏感文件的访问,例如 .htaccess
文件。可以使用以下配置:
location ~ /\.ht {
deny all;
}
这段配置会拒绝对以 .ht
开头的文件的所有访问请求。
3. 注意事项
- 正则表达式的使用:在
rewrite
指令中,正则表达式用于匹配请求的 URI。 - 标志参数的选择:根据实际需求选择合适的标志参数,如
last
、break
、redirect
或permanent
。 - 配置顺序:
rewrite
指令的执行顺序是:首先执行 server 块的rewrite
指令,然后是 location 块的匹配,最后是选定的 location 中的rewrite
指令。
通过合理使用 rewrite
指令,我们可以灵活地控制请求的 URL,实现各种重写和重定向需求。