WordPress 伪静态规则设置:Apache 和 Nginx 完整指南

本文介绍了WordPress伪静态(URL重写)在SEO和用户体验中的重要性,并提供了Apache和Nginx服务器的详细配置指南。重点解析了Apache服务器中.htaccess文件的基础规则与完整优化版配置,涵盖URL重写、HTTPS强制跳转、缓存控制、Gzip压缩及安全头部设置等核心优化步骤,帮助提升网站性能与安全性。

文章作者:曾凤祥
阅读时间: 83 分钟
更新时间:2026年4月16日

伪静态(URL重写)是WordPress SEO优化和用户体验的重要组成部分。以下是详细的Apache和Nginx伪静态规则配置指南。

📁 核心文件:.htaccess 和 nginx.conf

1. Apache 服务器 (.htaccess)

基础规则(WordPress自动生成)

在WordPress后台 设置 → 固定链接​ 中保存后,会自动生成:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

完整优化版 .htaccess

# 开启重写引擎
RewriteEngine On
RewriteBase /

# 设置默认字符集
AddDefaultCharset UTF-8

# 禁止目录浏览
Options -Indexes

# 1. 基础WordPress规则
# 如果请求的不是真实文件或目录,重写到index.php
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# 2. 强制 WWW 或非 WWW(二选一)
# 强制 www
RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [L,R=301]

# 强制 非www
RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com [NC]
RewriteRule ^(.*)$ https://yourdomain.com/$1 [L,R=301]

# 3. 强制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 4. 移除URL末尾的斜杠
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

# 5. 禁止直接访问敏感文件
<FilesMatch "^\.(htaccess|htpasswd|ini|log|sh|sql)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# 6. 阻止图片盗链
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com/.*$ [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,NC]

# 7. 缓存控制
<IfModule mod_expires.c>
    ExpiresActive On
    
    # 图片缓存1年
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    
    # CSS和JS缓存1个月
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    
    # 字体缓存1年
    ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
    ExpiresByType application/x-font-ttf "access plus 1 year"
    ExpiresByType application/x-font-opentype "access plus 1 year"
    ExpiresByType application/x-font-woff "access plus 1 year"
    
    # 默认缓存2天
    ExpiresDefault "access plus 2 days"
</IfModule>

# 8. Gzip压缩
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json application/xml application/rss+xml
</IfModule>

# 9. 安全头部
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

特定固定链接规则

根据不同的固定链接结构:

1. 数字型(默认)

http://example.com/?p=123

不需要特殊规则

2. 文章名型

http://example.com/sample-post/
# 在基础规则中已包含

3. 日期和文章名

http://example.com/2024/01/01/sample-post/
# WordPress自动处理

4. 自定义结构

/%category%/%postname%/
# 需要确保分类有slug
# 如果有中文字符分类,可能需要编码处理

多站点规则

# 子目录多站点
RewriteBase /
RewriteRule ^index\.php$ - [L]

# 如果请求的不是真实文件
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

# 子域名多站点
RewriteBase /
RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

2. Nginx 服务器配置

基础WordPress规则

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/wordpress;
    index index.php index.html index.htm;
    
    # 基础重写规则
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    
    # 处理PHP文件
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        
        # 安全设置
        fastcgi_param HTTP_PROXY "";
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }
    
    # 静态文件处理
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp)$ {
        expires max;
        log_not_found off;
        access_log off;
    }
    
    # 隐藏敏感文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    location ~ /(readme\.html|license\.txt|wp-config\.php|wp-config-sample\.php|wp-admin/install\.php) {
        deny all;
    }
}

完整优化版 Nginx 配置

# WordPress 优化配置
server {
    listen 80;
    listen 443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;
    
    # SSL证书(如果有)
    ssl_certificate /etc/nginx/ssl/yourdomain.com.crt;
    ssl_certificate_key /etc/nginx/ssl/yourdomain.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    root /var/www/wordpress;
    index index.php index.html index.htm;
    
    # 强制 HTTPS
    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }
    
    # 强制 www 或 非www
    if ($host = 'yourdomain.com') {
        return 301 https://www.yourdomain.com$request_uri;
    }
    
    # 1. 主重写规则
    location / {
        try_files $uri $uri/ /index.php?$args;
        
        # 移除URL末尾斜杠
        rewrite ^/(.*)/$ /$1 permanent;
    }
    
    # 2. PHP处理
    location ~ \.php$ {
        try_files $uri =404;
        
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        
        # 缓冲区优化
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
        
        # 超时设置
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 60s;
        
        # 不记录静态文件404错误
        fastcgi_intercept_errors off;
    }
    
    # 3. 静态文件缓存
    location ~* \.(css|js|ico|gif|jpeg|jpg|webp|png|svg|eot|otf|ttf|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        add_header Vary "Accept-Encoding";
        log_not_found off;
        access_log off;
        
        # 防止盗链
        valid_referers none blocked server_names *.yourdomain.com;
        if ($invalid_referer) {
            return 403;
        }
    }
    
    # 4. 字体文件
    location ~* \.(eot|otf|ttf|woff|woff2)$ {
        add_header Access-Control-Allow-Origin *;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # 5. 安全设置
    # 禁止访问敏感文件
    location ~ /\.(ht|git|svn) {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    location ~ /(readme\.html|license\.txt|wp-config\.php|wp-config-sample\.php|wp-admin/install\.php|xmlrpc\.php) {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    # 6. 上传文件优化
    location ~* /wp-content/uploads/.*\.php$ {
        deny all;
    }
    
    location /wp-content/uploads/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        
        # 尝试直接访问文件
        try_files $uri $uri/ /index.php?$args;
    }
    
    # 7. Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_min_length 1000;
    gzip_types
        application/atom+xml
        application/geo+json
        application/javascript
        application/x-javascript
        application/json
        application/ld+json
        application/manifest+json
        application/rdf+xml
        application/rss+xml
        application/xhtml+xml
        application/xml
        font/eot
        font/otf
        font/ttf
        image/svg+xml
        text/css
        text/javascript
        text/plain
        text/xml;
    
    # 8. 安全头部
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # 9. 防止注入攻击
    location ~* "(<|%3C).*script.*(>|%3E)" {
        return 403;
    }
    
    # 10. 多站点支持
    # 子目录多站点
    if (!-e $request_filename) {
        rewrite /wp-admin$ $scheme://$host$uri/ permanent;
        rewrite ^(/[^/]+)?(/wp-.*) $2 last;
        rewrite ^(/[^/]+)?(/.*\.php) $2 last;
    }
}

宝塔面板特定配置

如果你使用宝塔面板,在网站设置中添加:

# 宝塔面板 - WordPress优化规则
location / {
    index index.html index.php; 
    
    if (-f $request_filename/index.html){ 
        rewrite (.*) $1/index.html break; 
    } 
    
    if (-f $request_filename/index.php){ 
        rewrite (.*) $1/index.php; 
    } 
    
    if (!-f $request_filename){ 
        rewrite (.*) /index.php; 
    } 
}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    expires 30d;
    error_log off;
    access_log off;
}

location ~ .*\.(js|css)?$ {
    expires 12h;
    error_log off;
    access_log off; 
}

🔧 配置步骤

Apache 配置步骤

# 1. 启用rewrite模块
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires

# 2. 修改Apache配置
sudo nano /etc/apache2/sites-available/000-default.conf

# 在VirtualHost块内添加
<Directory /var/www/html>
    AllowOverride All
    Require all granted
</Directory>

# 3. 重启Apache
sudo systemctl restart apache2

# 4. 确保.htaccess文件可写
sudo chmod 644 /var/www/html/.htaccess
sudo chown www-data:www-data /var/www/html/.htaccess

Nginx 配置步骤

# 1. 创建WordPress配置文件
sudo nano /etc/nginx/sites-available/wordpress

# 2. 添加上面的Nginx配置
# 3. 创建符号链接
sudo ln -s /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/

# 4. 测试配置
sudo nginx -t

# 5. 重启Nginx
sudo systemctl restart nginx

# 6. 设置目录权限
sudo chown -R www-data:www-data /var/www/wordpress
sudo chmod -R 755 /var/www/wordpress

🐛 常见问题解决

问题1:404错误

Apache解决方案:

# 检查mod_rewrite是否启用
sudo a2enmod rewrite
sudo systemctl restart apache2

# 检查.htaccess权限
ls -la /var/www/html/.htaccess

Nginx解决方案:

# 确保try_files规则正确
location / {
    try_files $uri $uri/ /index.php?$args;
}

# 检查PHP配置
location ~ \.php$ {
    # fastcgi_param SCRIPT_FILENAME 必须设置正确
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

问题2:固定链接不工作

# Apache: 检查AllowOverride
# 确保httpd.conf或虚拟主机中有
AllowOverride All

# Nginx: 检查location规则
# 确保在location / {} 块中有正确规则

问题3:多站点伪静态

子目录多站点(Apache):

# 在.htaccess中添加
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

子域名多站点(Nginx):

server {
    listen 80;
    server_name ~^(www\.)?(?<sname>.+?)\.yourdomain\.com$;
    root /var/www/wordpress;
    
    index index.php;
    
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

问题4:中文URL编码问题

# Nginx中文URL支持
charset utf-8;
# 在location / 中添加
if (-f $request_filename) {
    break;
}
if (-d $request_filename) {
    break;
}

# 或者使用重写规则
rewrite /([^/]*)$ /index.php?name=$1 last;

📊 性能优化规则

Apache性能优化

# 在.htaccess中添加
<IfModule mod_expires.c>
    # 启用缓存
    ExpiresActive On
    
    # 默认缓存1小时
    ExpiresDefault "access plus 1 hour"
    
    # 图片缓存1年
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    
    # CSS、JS缓存1个月
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

# 启用压缩
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>

Nginx性能优化

# 在server块中添加
# 1. 启用Gzip
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/xml+rss
    application/json
    image/svg+xml;

# 2. 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|webp)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
    add_header Vary "Accept-Encoding";
    
    # 开启文件打开优化
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

# 3. 客户端缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

🛡️ 安全加固规则

Apache安全规则

# 1. 防止目录浏览
Options -Indexes

# 2. 保护敏感文件
<FilesMatch "^(wp-config\.php|php\.ini|\.htaccess)">
    Order allow,deny
    Deny from all
</FilesMatch>

# 3. 防止SQL注入
RewriteCond %{QUERY_STRING} (;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|cast|set|declare|drop|update|md5|benchmark) [NC,OR]
RewriteCond %{QUERY_STRING} \.\./\.\. [OR]
RewriteCond %{QUERY_STRING} (localhost|loopback|127\.0\.0\.1) [NC,OR]
RewriteCond %{QUERY_STRING} \:[0-9] [OR]
RewriteCond %{QUERY_STRING} (GLOBALS|REQUEST)(=|\[|%) [NC]
RewriteRule .* - [F,L]

# 4. 防止文件包含
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (javascript:).*(;) [NC,OR]
RewriteCond %{QUERY_STRING} (base64_encode).*\(.*\) [NC,OR]
RewriteCond %{QUERY_STRING} (img src=).*(;) [NC]
RewriteRule .* - [F,L]

Nginx安全规则

# 1. 禁止访问敏感文件
location ~ /\.(ht|git|svn) {
    deny all;
    access_log off;
    log_not_found off;
}

location ~* /(?:uploads|files|wp-content|wp-includes)/.*\.php$ {
    deny all;
}

# 2. 防止SQL注入
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
    set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
    return 403;
}

# 3. 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 444;
}

# 4. 防止图片盗链
location ~* \.(jpg|jpeg|png|gif|webp)$ {
    valid_referers none blocked server_names *.yourdomain.com;
    if ($invalid_referer) {
        return 403;
    }
}

🔄 重定向规则

通用重定向规则

Apache (.htaccess):

# 1. 重定向旧链接
Redirect 301 /old-page/ /new-page/

# 2. 重定向带参数的链接
RewriteCond %{QUERY_STRING} ^p=([0-9]*)$
RewriteRule ^$ /?p=%1 [R=301,L]

# 3. 重定向整个目录
RedirectMatch 301 ^/old-directory/(.*)$ /new-directory/$1

Nginx:

# 1. 重定向旧链接
rewrite ^/old-page/$ /new-page/ permanent;

# 2. 重定向非www到www
if ($host = 'yourdomain.com') {
    return 301 https://www.yourdomain.com$request_uri;
}

# 3. 重定向HTTP到HTTPS
if ($scheme = http) {
    return 301 https://$server_name$request_uri;
}

📝 调试方法

调试Apache重写

# 1. 启用重写日志
# 在虚拟主机配置中添加
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

# 2. 检查日志
sudo tail -f /var/log/apache2/rewrite.log

# 3. 测试.htaccess
sudo apachectl configtest

调试Nginx重写

# 1. 测试配置
sudo nginx -t

# 2. 检查错误日志
sudo tail -f /var/log/nginx/error.log

# 3. 添加调试日志
# 在nginx配置中添加
rewrite_log on;
error_log /var/log/nginx/rewrite.log notice;

🎯 最佳实践总结

  1. Apache用户
    • 确保 AllowOverride All已设置
    • 启用 mod_rewrite模块
    • 定期检查 .htaccess语法
  2. Nginx用户
    • 使用 try_files指令
    • 正确配置 fastcgi_param
    • 启用Gzip和缓存
  3. 通用建议
    • 始终备份原配置文件
    • 修改后重启服务
    • 使用工具测试URL
    • 监控错误日志
    • 定期更新规则
  4. 工具推荐
    • 在线.htaccess测试器
    • Nginx配置测试器
    • WordPress的”Rewrite Rules Inspector”插件
    • 浏览器开发者工具网络面板

通过以上配置,你可以确保WordPress的伪静态规则正确工作,同时获得更好的性能和安全性。

这篇文章有用吗?

点击星号为它评分!

平均评分 5 / 5. 投票数: 1

到目前为止还没有投票!成为第一位评论此文章。

在AI工具中继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为5000多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

无论你是否已有网站,我们都能帮你把线上业务推上新高度

从0到1,快速搭建专业线上业务平台

从0到1,快速搭建专业线上业务平台

无论您从事何种行业,小兽WordPress​ 都能为您提供专业、可定制、易维护的网站构建方案。我们精选多款高品质模板,适用于展示型官网、品牌形象站、外贸独立站等多种场景,助您快速上线,抢占市场先机。无需代码,轻松启动,即享专业设计。

立即查看所有模版
已有网站?我们来帮你加速、优化、变现

已有网站?我们来帮你加速、优化、变现

您的网站是否遇到加载慢、跳出率高、SEO停滞、体验老旧等问题?这不仅影响技术表现,更会导致客户流失与增长瓶颈。小兽WordPress​ 为您提供全面诊断、提速优化与价值深耕服务,通过“技术+策略”双驱动,助力网站高效转化,推动业务持续增长。

马上获取专属优化方案
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部