📜 ⬆️ ⬇️

Useful Snippets for Nginx Configs



Good day, dear habravchane! In Elasticweb, we secretly support Nginx and, probably, we are one of the few hosting sites that do not support Apache and .htaccess, respectively. In this regard, a large number of calls to those. support is associated with assisting in writing a configuration file for Nginx. Therefore, we decided to assemble a collection of useful snippets and a collection of ready-made Nging configs for the most popular CMS / CMF / Framework for PHP.


')

Ready configs:




Nginx commands



Basic commands for performing basic operations while running Nginx.



PHP location block


A simple template for quick and easy installation of PHP, FPM or CGI to your site.

location ~ \.php$ { try_files $uri =404; client_max_body_size 64m; client_body_buffer_size 128k; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/path/to/php.sock; } 


Rewrite and Redirection


Force www

The correct way to identify a remote server by domain without www and redirect it to www :

 server { listen 80; server_name example.org; return 301 $scheme://www.example.org$request_uri; } server { listen 80; server_name www.example.org; ... } 

Also works for https.

Force no-www

The correct way to determine the remote server for the domain c www and redirect it without www :

 server { listen 80; server_name example.org; } server { listen 80; server_name www.example.org; return 301 $scheme://example.org$request_uri; } 


Force HTTPS

Method for redirecting from HTTP to HTTPS:

 server { listen 80; return 301 https://$host$request_uri; } server { listen 443 ssl; # let the browsers know that we only accept HTTPS add_header Strict-Transport-Security max-age=2592000; ... } 


Force trailing slash

This line adds a slash / at the end of each URL, only in that case if the URL does not have a dot or parameters. Ie after example.com/index.php or example.com/do?some=123 slash is not set.

 rewrite ^([^.\?]*[^/])$ $1/ permanent; 


Redirect to page

 server { location = /oldpage.html { return 301 http://example.org/newpage.html; } } 


Redirect to the site

 server { server_name old-site.com return 301 $scheme://new-site.com$request_uri; } 


Redirect to a specific path in a URI

 location /old-site { rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent; } 


Performance


Caching

Allow browsers to permanently cache static content. Nginx will install both headers: Expires and Cache-Control.

 location /static { root /data; expires max; } 


You can disable browser caching (for example, to track requests) as follows:

 location = /empty.gif { empty_gif; expires -1; } 


Gzip compression


 gzip on; gzip_buffers 16 8k; gzip_comp_level 6; gzip_http_version 1.1; gzip_min_length 256; gzip_proxied any; gzip_vary on; gzip_types text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml text/javascript application/javascript application/x-javascript text/x-json application/json application/x-web-app-manifest+json text/css text/plain text/x-component font/opentype application/x-font-ttf application/vnd.ms-fontobject image/x-icon; gzip_disable "msie6"; 


File cache

If you cache a large number of static files through Nginx, then caching the metadata of these files will save the delay time.

 open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; 


SSL cache

Connecting SSL caching will allow you to resume the SSL session and reduce the time for the following calls to the SSL / TLS protocol.

 ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; 


Upstream support

Activating caching using upstream connections:

 upstream backend { server 127.0.0.1:8080; keepalive 32; } server { ... location /api/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Connection ""; } } 


Monitoring

By default, the Stub Status module is not built, its assembly must be enabled using the —with-http_stub_status_module configuration parameter and activated using:

 location /status { stub_status on; access_log off; } 


This setting will allow you to receive status in plain text format for the total number of requests and client connections (accepted, processed, active).

More informative status from Nginx can be obtained using Luameter , which is somewhat more complicated to install and requires the Nginx Lua module. It will provide the following metrics for various configuration groups in JSON format:



Luameter dashboard example .

Also ngxtop is great for collecting statistics.

Security


Activate Basic Authentication

First you need to create a password and save it in a plain text file:

 : 


Then set up the nickeys for the server / location of the block you want to protect:

 auth_basic "This is Protected"; auth_basic_user_file /path/to/password-file; 


Open local access only


 location /local { allow 127.0.0.1; deny all; ... } 


SSL security settings




Other


Subqueries after completion

There are situations when you need to transfer a request to another backend in addition or after its processing . The first case is to track the number of completed downloads by calling the API after the user has downloaded the file. The second case is to track the request to which you would like to return as quickly as possible (possibly with an empty .gif) and make the corresponding entries in the background. post_action , which allows you to define a subquery and will be rejected at the end of the current request - is the best solution for both options.

 location = /empty.gif { empty_gif; expires -1; post_action @track; } location @track { internal; proxy_pass http://tracking-backend; } 


Resource allocation between sources

The easiest and most well-known method of cross-domain request to your server:

 location ~* .(eot|ttf|woff) { add_header Access-Control-Allow-Origin *; } 


Sources





Thank you all very much for your attention!

Source: https://habr.com/ru/post/272381/


All Articles