0

Wondering if anyone with some nginx experience could help me out with a rewrite rule issue I'm having.

I want to remove .html and trailing slashes from my URLs, so I put the following code in the server { } block in the nginx conf.d file:

error_page 404 404.html;
rewrite ^(/.+)\.html$ $1;
rewrite ^/(.*)/$ /$1 permanent;
try_files $uri.html $uri/ =404;

This works great, but it's broken the images on my site. I have them in a folder Images, so in my HTML it's like <img src="Images/someImage.jpg">. They used to show up fine prior to adding the rewrite code, but now they don't load, and when I inspect them the Chrome console says "Failed to load resource: net::ERR_TOO_MANY_REDIRECTS", and beside that it says http://example.com/Images/404.html

If anyone knows what I'm doing wrong here, and could point me in the right direction, I'd greatly appreciate it!

L. Thane
  • 3
  • 1
  • 1
    Please post more clear examples of the URLs, what they are currently, what do you want them to be and exactly where. Edit this information into the question. – Tero Kilkanen Apr 04 '17 at 08:42

1 Answers1

0

There are a few different ways to go about removing the .html extension. One of them is.

rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;    # removing .html 
rewrite ^/(.*)/$ /$1 permanent;               # removing Trailing Slashes

we have to make sure Nginx knows what files to look for, basically all files with .html extension even index files, eg index.html So final code will be something like this.

server { 
        # define you server name listen port etc.
        .......
        .......
        .......

        rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;    # removing .html 
        rewrite ^/(.*)/$ /$1 permanent;               # removing Trailing Slashes

        # defining index with index.html, you can make it home.html or whatever you like.
        index index.html;                               

        # try getting only html files.
        try_files $uri/index.html $uri.html $uri/ $uri =404; 

        # defining error pages.
        error_page 404 /404.html; 
        error_page 500 502 503 504 /500.html;
}
  • 1
    Thanks mate! I edited the .html rewrite to your version, removed my error_page and try_files lines (the /etc/nginx/nginx.conf file already had the default error_page lines which work), and added your try_files line, and it's now working perfectly. Cheers! (Sorry, can't upvote yet, I'll be back when I have more reputation.) – L. Thane Apr 04 '17 at 13:58