Wiki source code of Nginx: useful configuration directives
Version 2.1 by Alexandru Pentilescu on 2023/01/08 13:17
Hide last authors
author | version | line-number | content |
---|---|---|---|
![]() |
1.1 | 1 | (% class="jumbotron" %) |
2 | ((( | ||
3 | (% class="container" %) | ||
4 | ((( | ||
5 | = Nginx: useful configuration directives = | ||
6 | This article will function along the lines of a //Tips and tricks//-style article, where I'll be showing off various configuration directives for nginx to use in the wild to achieve specific purposes. | ||
7 | Hopefully, this article will grow over time. | ||
8 | ))) | ||
9 | ))) | ||
10 | |||
11 | (% class="row" %) | ||
12 | ((( | ||
13 | (% class="col-xs-12 col-sm-8" %) | ||
14 | ((( | ||
15 | |||
16 | = Mapping a specific URL location to a directory location on the system = | ||
17 | |||
18 | Sometimes, you may want a very simple configuration where you have a specific URL location (i.e. **https://pentilescu.com/bin/**) and you want this URL prefix to indicate to Nginx to use a specific directory on the system to look for the requested files in. Or, in other words, every HTTP GET request sent to **https://pentilescu.com/bin/** (e.g. **https://pentilescu.com/bin/folder1/myfile.png**) to be searched for in a specific systems directory (e.g. **/var/www/static/**). This way, a request for **https://pentilescu.com/bin/folder1/myfile.png** should resolve to **/var/www/static/folder1/myfile.png**. How do we do this? | ||
19 | |||
20 | Simple! We use the "alias" directive, like so! | ||
21 | |||
22 | {{code language="nginx"}} | ||
23 | server { | ||
24 | server_name pentilescu.com; | ||
25 | |||
26 | location /robots.txt { | ||
27 | alias /var/www/static/robots.txt; | ||
28 | } | ||
29 | |||
30 | location /sitemap.xml { | ||
31 | alias /var/www/static/sitemap.xml; | ||
32 | } | ||
33 | |||
34 | location /bin/ { | ||
35 | alias /var/www/static/; | ||
36 | } | ||
37 | |||
38 | location / { | ||
39 | return 301 https://alexandru.pentilescu.com$request_uri; | ||
40 | } | ||
41 | |||
42 | listen 80; | ||
43 | listen [::]:80; | ||
44 | listen 443 ssl; | ||
45 | listen [::]:443; | ||
46 | } | ||
47 | {{/code}} | ||
48 | |||
49 | Please note that the most important part of that snippet is the **location /bin/** directive, followed by the **alias**, which tells nginx to map all GET requests sent to the **/bin/** URL to the **/var/www/static** directory. | ||
50 | |||
51 | The other directories above it (i.e. the **location /robots.txt** directive) also use the **alias** directive, but they use it to map to a specific file location, rather than a directory location. This is also possible. | ||
52 | ))) | ||
53 | |||
54 | |||
55 | (% class="col-xs-12 col-sm-4" %) | ||
56 | ((( | ||
57 | {{box title="**Contents**"}}{{toc /}}{{/box}} | ||
58 | |||
59 | ))) | ||
60 | ))) |