The Computer Oracle

Get Nginx to always serve index

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Get Nginx To Always Serve Index
00:46 Accepted Answer Score 18
01:02 Answer 2 Score 3
02:08 Answer 3 Score 0
02:23 Thank you

--

Full question
https://superuser.com/questions/1199616/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#nginx

#avk47



ACCEPTED ANSWER

Score 18


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.




ANSWER 2

Score 3


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 www.example.com:

server {
    listen 80;
    server_name www.example.com;

    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 (https://askubuntu.com/a/134676) and on the topic of how to display current URL from PHP (https://stackoverflow.com/a/6768831).




ANSWER 3

Score 0


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.