I’m having trouble with my Nginx configuration for a WordPress site. I want to redirect Australian users to a different site, but the issue isn’t with the redirection itself. The problem arises whenever I use an if condition in my Nginx config.
The redirection works fine for the root domain (https://example.com/), but when users try to access a subpage like https://example.com/contact/, they get a 404 error.
Here’s my Nginx config:
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
include snippets/self-signed.conf;
include snippets/ssl-params.conf;
server_name example.com;
root /var/www/html/example-new;
index index.php;
location / {
set $should_redirect 0;
if ($http_cf_ipcountry = AU) {
set $should_redirect 1;
}
if ($should_redirect) {
return 301 $redirect_au;
}
try_files $uri $uri/ /index.php?$args;
}
location ~ .php$ {
include fastcgi_params;
fastcgi_intercept_errors on;
fastcgi_pass fastcgi_backend;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
In the error log, I see:
2024/06/16 12:39:37 [error] 814049#814049: *13 "/var/www/html/example-new/contact/index.php" is not found (2: No such file or directory), client: 172.68.200.152, server: example.com, request: "GET /contact/ HTTP/1.1", host: "www.example.com", referrer: "https://www.example.com/"
This issue occurs whenever an if condition is present, regardless of its content. If any if condition value is true, I get this error. There is no issue with the redirection part; if I comment out the if ($should_redirect) { return 301 $redirect_au; } line, the root domain and subdirectories work fine even if there is an if condition.
It seems like Nginx is trying to find contact/index.php, but there is no index.php file in the subdirectory, which is expected for WordPress.
I don’t want to use any plugins as a solution. How can I fix my Nginx configuration to handle if conditions without causing 404 errors on subpages?
I expected the if condition to be evaluated without causing 404 errors on subpages. It seems like Nginx is trying to find contact/index.php, but there is no index.php file in the subdirectory, which is expected for WordPress.
How can I fix my Nginx configuration to handle if conditions without causing 404 errors on subpages?