Report this

What is the reason for this report?

Nginx rewriterule URL without extension

Posted on March 16, 2021
Kris

By Kris

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:

Thanks



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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.

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

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.