Nginx remove html from url

If you have a static website build using plain html files, your url will look like https://yourdomain/page.html. This .html extension is useful for the files when it is on your local computer, it help computer to associate the file with specific application, say your HTML editor. But on a web server this .html extension serve no purpose. If you are using Nginx web server, you can remove .html extension from your web page urls with following code.

location / {
    if ($request_uri ~ ^/(.*)\.html$) {
        return 301 /$1;
    }
    try_files $uri $uri.html $uri/ =404;
}

Remove .php extension

To remove .php extension, you can use

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

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

Reataining Arguments

To retain arguments, use

Advertisement

return 301 /$1$is_args$args;

This will redirect /mypage.html?name= to /mypage?name=

Serve PHP file with .html extension

Add a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Advertisement