You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx添加请求方法限制时报‘unexpected }’错误求助

解决Nginx配置中添加请求方法限制规则的语法错误

你遇到的“unexpected }”错误是因为添加的规则里存在语法错误:return 405;s末尾多了一个多余的s,导致Nginx解析配置时出现语法异常。

修正后的请求方法限制规则

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

整合后的完整WordPress Nginx配置

将修正后的规则放在server块内的全局位置(建议在client_max_body_size之后、第一个location块之前),完整配置如下:

server {
    listen 80;
    listen [::]:80;
    root /var/www/html/wpress; 
    index index.php index.html index.htm;
    server_name wpress.conf www.wpress.conf;
    error_log /var/log/nginx/wpress.conf_error.log;
    access_log /var/log/nginx/wpress.conf_access.log;
    client_max_body_size 100M;

    # 限制仅允许GET/HEAD/POST请求方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }
}

验证与生效

配置修改完成后,执行以下命令验证语法正确性:

nginx -t

若输出提示test is successful,则重启Nginx服务使配置生效:

systemctl restart nginx

内容的提问来源于stack exchange,提问作者Savage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:37:46