插件窝 干货文章 Nginx怎么设置wordpress伪静态

Nginx怎么设置wordpress伪静态

WordPress Nginx 配置 location 842    来源:    2025-04-23

Nginx WordPress伪静态设置指南

在Nginx服务器上设置WordPress伪静态需要正确配置Nginx的rewrite规则。以下是详细步骤:

1. 基本伪静态配置

在Nginx的站点配置文件中(通常在/etc/nginx/sites-available/your-site.conf),添加以下location块:

server {
    # ... 其他配置 ...

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # ... 其他配置 ...
}

2. 完整的WordPress Nginx配置示例

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/wordpress;
    index index.php index.html index.htm;

    access_log /var/log/nginx/wordpress.access.log;
    error_log /var/log/nginx/wordpress.error.log;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ /\. {
        deny all;
    }
}

3. WordPress后台设置

  1. 登录WordPress后台
  2. 进入"设置" > "固定链接"
  3. 选择你喜欢的URL结构(如"文章名")
  4. 点击"保存更改"

4. 测试和重载配置

# 测试Nginx配置是否正确
sudo nginx -t

# 重载Nginx配置
sudo systemctl reload nginx

常见问题解决

  1. 出现404错误

    • 确保Nginx配置中的root路径正确指向WordPress安装目录
    • 确认.php文件的处理配置正确
    • 检查文件权限是否正确
  2. 重定向循环

    • 确保没有重复的rewrite规则
    • 检查WordPress的wp-config.phpWP_HOMEWP_SITEURL设置是否正确
  3. 特定页面无法访问

    • 尝试在WordPress后台重新保存固定链接设置
    • 检查Nginx错误日志获取更多信息

多站点配置

如果你使用WordPress多站点,需要使用不同的rewrite规则:

location / {
    try_files $uri $uri/ /index.php?$args;
}

rewrite /wp-admin$ $scheme://$host$uri/ permanent;

完成以上设置后,你的WordPress网站应该能够正常使用伪静态URL了。