Skip to content
Advertisement

How redirect from /file.php to /file on nginx?

I’m currently hiding the .php extension from the urls on my nginx server with this configuration:

JavaScript

This is working perfectly, but how can I make nginx not allow adding the .php extension?. In my example if you manually delete the .php it works but if you add it it remains permanent in the url.

Advertisement

Answer

To redirect those requests permanently with HTTP 301 code try

JavaScript

Put this directive before your location blocks.

Update

After this being answered, OP asked another question (now being deleted) – what if you have the following webroot structure:

JavaScript

Previous solution makes it impossible to serve somename.php file, because the request to http://example.com/somename would be redirected by try_files directive to http://example.com/somename/ and in next turn would be served with somename/index.php file.

This can be solved, but you’ll have to stop using index and try_files directives and emulate their behavior with your own request processing logic. This is what I’ve ended up with:

JavaScript

With this configuration and webroot structure given above

  • request to http://example.com/ would be served with webroot/index.php file;
  • request to http://example.com/somename would be served with webroot/somename.php file;
  • request to http://example.com/somename.php would be redirected to http://example.com/somename and served with webroot/somename.php file;
  • request to http://example.com/somename/ would be served with webroot/somename/index.php file;
  • request to http://example.com/someothername would be redirected to http://example.com/someothername/ (since no webroot/someothername.php file exists) and served with webroot/someothername/index.php file.

Important note about custom HTTP error pages

If you have some custom error page, for example webroot/error/404.php for HTTP 404 error, instead of usual way to define it like

JavaScript

you’d need to skip .php extension of that file:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement