伪静态(URL重写)是Nginx中常用的功能,用于将动态URL转换为看起来像静态URL的形式,提高SEO友好性和用户体验。
Nginx的伪静态规则主要通过rewrite
指令实现:
rewrite regex replacement [flag];
rewrite ^/oldpage$ /newpage permanent;
rewrite ^/(.*)$ /index.php/$1 last;
# 将 /article/123 重写为 /article.php?id=123
rewrite ^/article/(\d+)$ /article.php?id=$1 last;
# 将 /product/5/category/12 重写为 /product.php?id=5&cat=12
rewrite ^/product/(\d+)/category/(\d+)$ /product.php?id=$1&cat=$2 last;
rewrite ^(.*)$ https://$host$1 permanent;
last
:停止处理当前rewrite指令,继续匹配locationbreak
:停止处理所有rewrite指令redirect
:返回302临时重定向permanent
:返回301永久重定向server {
listen 80;
server_name example.com;
location / {
# 如果请求的不是真实存在的文件或目录
if (!-e $request_filename) {
# 重写到index.php作为入口
rewrite ^/(.*)$ /index.php/$1 last;
}
}
# 文章伪静态规则
location /article {
rewrite ^/article/(\d+)$ /article.php?id=$1 last;
}
# 产品伪静态规则
location /product {
rewrite ^/product/([a-z]+)/(\d+)$ /product.php?type=$1&id=$2 last;
}
}
nginx -t && nginx -s reload
return
指令对于简单重定向更高效nginx
rewrite_log on;
error_log /var/log/nginx/error.log notice;
希望这些信息能帮助您定义Nginx伪静态规则。根据您的具体应用场景,可能需要调整这些示例规则。