在 NGINX 中实现伪
静态主要是通过
rewrite指令或者
location块来重写 URL。以下是一些常见的伪静态规则配置示例,你可以根据自己的需求进行调整。
将动态 URL 转换为静态形式,例如将
index.php?id=123转换为
article/123.html:
server {
listen 80;
server_name example.com;
root /path/to/your/website;
# 启用PHP支持
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 伪静态规则:将/article/123.html重写为index.php?id=123
location /article/ {
rewrite ^/article/([0-9]+)\.html$ /index.php?id=$1 last;
}
# 其他静态文件直接访问
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires max;
log_not_found off;
}
}
WordPress 默认使用动态 URL,通过以下规则可以启用漂亮的永久链接:
server {
listen 80;
server_name example.com;
root /path/to/wordpress;
index index.php index.html;
# 启用PHP支持
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# WordPress伪静态规则
location / {
try_files $uri $uri/ /index.php?$args;
}
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires max;
log_not_found off;
}
}
对于包含多个参数的 URL,可以使用更复杂的重写规则。例如,将product.php?cat=1&item=23转换为product/cat1/item23.html:
server {
listen 80;
server_name example.com;
root /path/to/your/website;
# 启用PHP支持
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 多参数伪静态规则
location /product/ {
rewrite ^/product/cat([0-9]+)/item([0-9]+)\.html$ /product.php?cat=$1&item=$2 last;
}
# 静态文件处理
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires max;
log_not_found off;
}
}
1.修改 NGINX 配置后,需要重新加载配置:
sudo nginx -s reload
2.确保服务器有足够的权限访问网站文件。
3.如果规则不生效,检查 NGINX 错误日志:
tail -f /var/log/nginx/error.log
-
使用last标记终止当前规则集的处理,使用break终止当前location块的处理。
-
复杂的重写规则可能会影响性能,尽量保持规则简洁。