Get Nginx to always serve index

How can I get nginx to always serve index.html no matter the URL?

For example, I want the URL to always serve

I don't want to use a re-direct, because the user must still have the original URL they typed in their address bar.

I changing Nginx config to re-direct 404's to index.html, but I don't think thats a great way of doing it because it will return a 404 response.

In future I may want to have the index.html display the original URL that the user accessed, is there a way to do this?

Thanks

3 Answers

The common pattern uses try_files with a default URI. For a minimalist example:

server { root /path/to/root; location / { try_files $uri $uri/ /index.html; }
}

See this document for more.

5

Answer to question 1:

The function you're looking for is called URL rewriting. This allows you to create masks (or "fake" URLs) which show resource that is located on different URL.

In Nginx this is achieved by rewrite <regexp-pattern> <target-url> command in configuration file. Here is Nginx configuration for domain

server { listen 80; server_name root /var/www/example.com; index index.html; rewrite ^.*$ /index.html;
}

The <regexp-pattern> (REGular EXPression) part is compared to url you've typed into browser - if the match is successful, resource at <target-url> is shown.

Answer to question 2:

The current URL cannot be shown with pure HTML document only. You will need to use server-side scripting language - for example PHP. This will allow you to display dynamic content to the user. There is inexhaustible supply of guides on PHP with Nginx () and on the topic of how to display current URL from PHP ().

This is the code you're looking for

server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /var/www/;
index index.html;
location = /favicon.ico { access_log off; log_not_found off; }
error_page 404 =200 /;
}

With server_name _; he listen from any ip, domain.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like