Question

Nginx rewriterule URL without extension

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


Submit an answer

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!

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

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 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 @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