How to correct syntax errors in NGINX config for WordPress

I’m experiencing issues with my NGINX configuration for my WordPress site. Each time I try to impose request method restrictions within my server block, I encounter syntax errors.

This is my existing configuration:

server {
    listen 80;
    listen [::]:80;
    
    root /var/www/html/mysite;
    index index.php index.html index.htm;
    
    server_name mysite.local www.mysite.local;
    
    error_log /var/log/nginx/mysite_error.log;
    access_log /var/log/nginx/mysite_access.log;
    
    client_max_body_size 100M;
    
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.0-fpm.sock;
    }
}

I am trying to add this snippet:

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

However, it continually results in “unexpected }” error regardless of where I insert it in the config. I’ve tested various locations, yet I can’t figure out how to implement request method filtering into my NGINX setup without encountering syntax issues.

This looks like a semicolon or missing braces issue. Check that you’ve got semicolons after each directive and wrap your if statement in a location block - don’t put it directly in the server context. I ran into the same thing upgrading WordPress. Some NGINX versions are pickier about where you place conditionals. Try moving it inside your main location / block, right after try_files. Also check for unclosed blocks above this server block - NGINX sometimes reports errors in the wrong spot when there’s a missing brace earlier in the config.

put the if statement right after server_name and before error_log. check for extra spaces or weird characters too - nginx hates that stuff. fixed it for me with the same problem.

Syntax looks fine, but NGINX is picky about where you put things. Move that if block inside your main location block - don’t put it at server level. Always run nginx -t before reloading to catch issues early. I’ve hit this before and found invisible characters from copy-pasted docs can break parsing. Just retype the if statement by hand instead of copying it. Also check your NGINX version - older ones sometimes choke on certain conditionals even when the syntax is technically correct.