Question

Nginx rewriterule URL without extension

Posted March 16, 2021 710 views
NginxUbuntuUbuntu 20.04

Hi

I followed this tutorial: https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-20-04

How can I add a rewrite rule for nginx that my pages are accessible like:

  • example.com/page instead of example.com/page.php
  • example.com/folder/page instead of example.com/folder/page.php
  • example.com/folder instead of example.com/folder/index.php

Thanks

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
3 answers

Hi @KrisL,

I’ve had a quick research on the topic and what I learned is that if you append your /etc/nginx/conf.d/domain.conf file to include:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    try_files $uri =404;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

Then restart Nginx and give it a go. Hopefully, this will help you!

The source of this can be found here More information can be found here Nginx extenshionless loading

Regards,
KFSys

Hi KFSys

I’ve tested this, but when I open the page, I get a ‘download’ popup.

server {
    listen 80;
    server_name www.example.local;
    root /var/www/vhosts/example/httpdocs;

    location / {
      try_files $uri $uri.php $uri/ @extensionless-php;
      index index.html index.htm index.php;
    }

    location ~ \.php$ {
      try_files $uri =404;
    }

    location @extensionless-php {
      rewrite ^(.*)$ $1.php last;
    }

    location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

}

Hi

I think I’ve figured it out. Can you please have a look to this? It works, but did I made any other mistakes to watch out for?

The pages are also accessible with their ’.php’ extension, like example.com/page.php
Does that hurt the SEO or something else?

server {
  listen 80;
  server_name www.example.local;
  root /var/www/vhosts/example/httpdocs;

  index index.html index.htm index.php;

  location / {
    try_files $uri $uri/ @ext;
  }

  location ~ \/\.php {
    rewrite "^(.*)\/.php" $1.php last;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
  }

  location @ext {
    rewrite "^(.*)$" $1.php;
  }
}

Thanks
Kris