regexnginxdigital-ocean

Remove index.php from URL in Nginx


my URLS should be in this format:

https://www.example.com/author/article-title

But Google tries to scan also:

https://www.example.com/index.php/author/article-title

I tried to solve this on Nginx with this rule:

location /index.php {
    try_files $uri/$1/$2 "$uri/index.php\/([a-z-0-9-]{2,})\/([a-z-0-9-]{2,})\/?";
}

If I try the right URL works, if I try the wrong one, the server responds with error 500. I want a redirect 301 to the right URL


Solution

  • I solved with (thanks for suggestions):

    robots.txt

    User-agent: *
    Disallow: /index.php
    

    nginx.conf

    location / {
        # Redirect requests containing 'index.php' to the same URL without it
        if ($request_uri ~* "/index.php(.*)") {
            return 301 $1$is_args$args;
        }
    
        try_files $uri $uri/ /index.php?$query_string;
    }