Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

Nginx exact uri match with separate folder for every URI

I have the next catalog tree

$pwd 
/var/www/my-site/my-site.com
$tree
.
├── landing_page
│?? ├── README.md
│?? ├── logo_no_bg_1.png
│?? ├── programmer.png
│?? ├── scratch.html
│?? ├── styles.css
│?? └── котик.jpg
└── term_of_service
    └── term_of_service.txt

I want that every request to my-site.com was returning a scratch.html and every request to my-site.com/term-of-service.txt was returning term_of_service.txt.

How I can do it?

My current config:

server {
listen              443 default_server ssl;
server_name my-site.com www.my-site.com;

ssl_certificate     /etc/letsencrypt/live/my-site.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem;
ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers         HIGH:!aNULL:!MD5;

root /var/www/my-site/my-site.com/ ;
index landing_page/scratch.html;

location term-of-service.txt {
  index term_of_service/term_of_service.txt;
    }

location / {
        try_files $uri $uri/ =404;
    }

}

question from:https://stackoverflow.com/questions/65880574/nginx-exact-uri-match-with-separate-folder-for-every-uri

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All Nginx URIs begin with a leading /.

Use location = syntax to exactly match a single URI. See this document for details.

There are a number of ways to select a single file from within a location block. The most explicit is to specify it as the first parameter of a try_files statement. See this document for details.

For example:

root /var/www/my-site/my-site.com;

location = /term-of-service.txt {
    try_files /term_of_service/term_of_service.txt =404;
}
location = / {
    try_files /landing_page/scratch.html =404;
}

If you want treat the landing_page directory as the document root, the term_of_service.txt file would be outside the document root and therefore require its own root statement inside the location block.

For example:

root /var/www/my-site/my-site.com/landing_page;

location / {
    index scratch.html;
    try_files $uri $uri/ =404;
}
location = /term-of-service.txt {
    root /var/www/my-site/my-site.com/term_of_service;
    try_files /term_of_service.txt =404;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...