0

I'm trying to automatically redirect pages with a PHP extension to a non extension page version e.g example.com/page.php to example.com/page. I've managed to get this working for all pages except my home page and a dynamic page. These pages both return a 404 error page.

For the home page if I try to visit example.com I get a 404 response, but if I visit example.com/index then the home page loads.

I obviously want the home page to load like example.com and the dynamic page should load like example.com/check/something.com.

Here's the relevant code:


server {

   index  index.php index.html index.htm;

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

        # returns a 404 e.g example.com/check/something.com
        rewrite ^/check/(.*)$ /check.php?url=$1&name=&submitBtn=check;
   }

    # If PHP extension then 301 redirect to semantic URL
    location ~ ^(.*)\.php$ {
        return 301  $scheme://$server_name$1$is_args$args;
    }

    location ~ ^/(.*) {
       try_files $uri.php @static; # If static, serve it in @static

       fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;

       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root/$1.php;
       fastcgi_param SCRIPT_NAME $fastcgi_script_name;

       include fastcgi_params;
    } 

    location @static {
        try_files $uri =404;
    }

  }


Thanks :)

  • Your location / { ... } block is never visited - because location ~ ^/(.*) will match any URI not ending with .php. – Richard Smith May 15 at 16:56
  • @Richard Smith, Thanks, what would be the best way to fix this? I need the location / block so can't really change it. I can't figure out how to redirect to non PHP pages without using location ~ ^/(.*) regex. – turrican_34 May 16 at 0:30
  • I don't understand why you need a location block that's never used. Your location ~ ^/(.*) block should be the location / block. The rewrite should be inside a location /check/ block. And the homepage should be inside a location = / block. – Richard Smith May 16 at 6:16
  • @Richard Smith, I've commented out the location / block and added the check and homepage block, but I'm still getting a 404 for both of them. location = / { try_files /index.php?$args; } location /check/ { rewrite ^/check/(.*)$ /check.php?url=$1&name=&submitBtn=check; } – turrican_34 May 16 at 11:05
  • Nginx will not restart with the edits in your comment as try_files has an incorrect number of parameters. You are internally rewriting to a URI ending with .php. You should be rewriting to /index and /check. – Richard Smith May 16 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.