1

Just learning basic NGINX. I am trying to rewrite some clean URLS so they redirect to files in a subdirectory called on the server called views.

The below config accomplishes this. However, whenever I return to the index page, it returns a 404 error.

As you'll see below, I define my index as index.html. I assumed this would ensure that the index.html be treated as the index file. However, it appears NGINX is opting to use the first location block to determine the index. That makes sense because '/' is the index. However, I am attempting to only use that first location block for subsequent pages (ie nginx-practice.test/secondpage)

Here's the config file:

server { listen 127.0.0.1:80; server_name nginx-practice.test; root /usr/robertguttersohn/Sites/nginx-practice/public; index index.html; location ~ /. { root /user/Sites/nginx-practice/public/views; try_files $uri @htmlext =404; } location @htmlext { rewrite ^(.*)$ $1.html last; } access_log /usr/local/var/log/nginx/access.log; error_log /usr/local/var/log/nginx/error.log; } 

How do I have NGINX use index.html for the index page and then use the rewrite for all subsequent pages?

1
  • You could use location = / {} to target index.html file just for the home page. Commented Mar 3, 2023 at 8:01

1 Answer 1

1

You could use location = / {} to target index.html file just for the home page and then use the generic location / {} block to target the subsequent pages. Here's an example...

server { listen 127.0.0.1:80; server_name nginx-practice.test; root /user/robertguttersohn/Sites/nginx-practice/public; index index.html; # To isolate home page location = / { try_files /index.html =404; } # To parse subsequent pages location / { root /user/robertguttersohn/Sites/nginx-practice/public/views; try_files $uri @url.html =404; } access_log /usr/local/var/log/nginx/access.log; error_log /usr/local/var/log/nginx/error.log; } 

As you can see, the location @htmlext {} block can be eliminated too.

In my example, I have used /user/robertguttersohn/Sites/nginx-practice/public as root directory and /user/robertguttersohn/Sites/nginx-practice/public/views as sub-directory. You may want to update it to fit your environment. Please remember to restart Nginx server after making any change in configuration.

For more info on how location works, please checkout https://nginx.org/r/location .

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.