Nginx usage and configuration

Posted by marque on Tue, 23 Jul 2019 06:41:40 +0200

 

 

Nginx Catalogue

$ cd /etc/nginx
$ ls -l
total 60
drwx------ 2 ubuntu ubuntu 4096 Jun 16 09:27 cert    ## ssl certificate directory
drwxr-xr-x 2 root   root   4096 Jul 12  2017 conf.d
-rw-r--r-- 1 root   root   1077 Feb 11  2017 fastcgi.conf
-rw-r--r-- 1 root   root   1007 Feb 11  2017 fastcgi_params
-rw-r--r-- 1 root   root   2837 Feb 11  2017 koi-utf
-rw-r--r-- 1 root   root   2223 Feb 11  2017 koi-win
-rw-r--r-- 1 root   root   3957 Feb 11  2017 mime.types
-rw-r--r-- 1 root   root   1501 Aug 31 07:42 nginx.conf    ## configuration file
-rw-r--r-- 1 root   root    180 Feb 11  2017 proxy_params
-rw-r--r-- 1 root   root    636 Feb 11  2017 scgi_params
drwxr-xr-x 2 root   root   4096 Aug 31 09:42 sites-available  ## Virtual Host Configuration Agent Directory
drwxr-xr-x 2 root   root   4096 Jun 15 06:39 sites-enabled    ## Start the configuration agent directory
drwxr-xr-x 2 root   root   4096 Jun  4 06:03 snippets
-rw-r--r-- 1 root   root    664 Feb 11  2017 uwsgi_params
-rw-r--r-- 1 root   root   3071 Feb 11  2017 win-utf

The relationship between nginx configuration files:

Common commands

## View the Nginx program file directory: / usr/sbin/nginx
$ ps  -ef | grep nginx

## Check the nginx.conf configuration file directory: / etc/nginx/nginx.conf
$ nginx -t                 
$ vim /etc/nginx/nginx.conf

## Configuration file directory: / etc/nginx

## Virtual Host Profile Directory: / etc/nginx/sites-available/
## Virtual Host Folder Directory: / var/www/, details can be configured in / etc/nginx/sites-available/.
## Default Web Page File Directory: / usr/share/nginx/html

## Test the configuration file to check only if there are syntax errors in the configuration file
$ nginx -t -c <path-to-nginx.conf>
$ sudo nginx -t -c /etc/nginx/nginx.conf

## Start the Nginx service
$ nginx Installation directory -c <path-to-nginx.conf>
$ sudo /etc/init.d/nginx start

## Stop the Nginx service
$ sudo /usr/sbin/nginx -s stop 

## Restart Nginx 
$ sudo /usr/sbin/nginx -s reload  # Method after version 0.8
$ kill -HUP pid     # Send a signal to the master process to restart Nginx calmly, i.e. the service is uninterrupted

$ sudo service nginx start
$ sudo service nginx stop
$ sudo service nginx restart

Official configuration notes:

(16) Recommend an HTTPS automated configuration tool: Mozilla SSL Configuration Generator

Nginx configuration file: / etc/nginx/nginx.conf

Configuration agent directory: / etc/nginx/sites-available/

  • Specific Server configuration files are stored in the sites-available directory.
  • The default configuration file: / etc/nginx/sites-available/default file configures the default virtual host directory root/var/www/html in detail, and the listening port is 80.

Start the configuration agent directory: / etc/nginx/sites-enabled/

  • Link files are stored in the sites-enabled directory. Each link file points to the configuration files in the sites-available directory, indicating which configuration agent files need to be enabled by Nginx.

  • The proxy configuration can be enabled by creating a configuration file under the sites-enabled symlink link sites-available.

    $ sudo ln -s /etc/nginx/sites-available/availableFileName linkFileName

  • Default enabled services: / etc/nginx/sites-enabled/ default soft link points to / etc/nginx/sites-available/default, deleting the link file closes the configuration agent.

nginx.conf configuration file

Nginx configuration file path: / etc/nginx/nginx.conf

##
# Global configuration
##

user www-data;             ## Configuring users and groups of worker processes
worker_processes auto;     ## Configure the number of worker process startups, and it is recommended to configure the number of CPU cores
error_log logs/error.log;  ## Global error log
pid /run/nginx.pid;        ## Files that record the ID of the main process
worker_rlimit_nofile 8192; ## Configure the maximum number of concurrent connections that a working process can accept

##
# Working mode and upper limit of connection number
##
events {
    # epoll is a way of multiplexing IO (I/O Multiplexing).
    # Nginx performance can be greatly improved by using only the Linux 2.6 or more kernels
    use epoll
        
    # Maximum number of concurrent links for a single background worker process
    # Concurrent total max_clients = worker_professes * worker_connections
    worker_connections 4096;  ## Defaule: 1024
    # multi_accept on;  ## Specify that the worker process accepts new connections immediately
}

##
# http module
##

http {

    ##
    # Basic Settings
    ##
    
    #The sendfile instruction specifies whether nginx calls the sendfile function (zero copy mode) to output the file.
    #For general applications, it must be set to on.
    #If it is used for downloading or other application disk IO heavy load applications, it can be set to off.
    #To balance disk and network I/O processing speed and reduce uptime of the system.
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;      ## Connection timeout
    types_hash_max_size 2048;  ## Specifies the maximum size of a hash type table
    # server_tokens off;

    # server_names_hash_bucket_size 64;  # this seems to be required for some vhosts
    # server_name_in_redirect off;
    
    include /etc/nginx/mime.types;  ## Setting mine Type
    default_type application/octet-stream;
   
    # Setting Request Buffer
    client_header_buffer_size    128k; # Specifies the size of the client request header cache, which is used when the request header is greater than 1KB
    large_client_header_buffers  4 128k; # Maximum number and maximum client request header size
    
    ##
    # SSL Settings
    ##
    
    # Enable all protocols, disable discarded unsafe SSL 2 and SSL 3
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    # Let the server select the algorithm suite to use
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;  ## Access Log
    error_log /var/log/nginx/error.log;    ## Error log

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;   # This folder is empty by default
    include /etc/nginx/sites-enabled/*; # Open Server Service Configuration

}

##
# mail module
##
        
mail {
    # See sample authentication script at:
    # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript

    # auth_http localhost/auth.php;
    # pop3_capabilities "TOP" "USER";
    # imap_capabilities "IMAP4rev1" "UIDPLUS";

    server {
        listen     localhost:110;
        protocol   pop3;
        proxy      on;
    }

    server {
        listen     localhost:143;
        protocol   imap;
        proxy      on;
    }
}

Virtual server configuration

Virtual server configuration file directory: / etc/nginx/sites-available/

Custom profile: sudo vim/etc/nginx/sites-available/arlingbc

Configure HTTP service (port 80)

# Virtual Host configuration for arlingbc.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#

# Discard requests that lack Host headers
server {
       listen 80;
       return 444;
}

server {
       listen 80;
       listen [::]:80;
       server_name example.com www.example.com;

       # Define the default site root location for the server
       root /var/www/example/;
       
       # Add index.php to the list if you are using PHP
       index index.html index.htm index.nginx-debian.html;

       # access log file access log
       access_log logs/nginx.access.log main;
       
       # Disallow access to hidden files
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
    
       # Default request
       location / {
                # First try to provide the request as a file, then as a directory, and then back to display 404.
                # The try_files instruction will be tried in the order given its parameters, and the first matched instruction will be used.
                # try_files $uri $uri/ =404;
      
                try_files $uri $uri/ /index.php?path_info=$uri&$args =404;
                access_log off;
                expires max;
       }
    
       # Static file, nginx handles by itself
       location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
           #30 days after expiration, the static files are not updated very much, the expiration can be set a little larger.
           #If you update frequently, you can set it up a little smaller.
           expires 30d;
       }
    
       # php request
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
       }
    
      # PHP script requests are all forwarded to FastCGI processing. Use the default configuration of FastCGI.
      # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
      #
      #location ~ \.php$ {
      #       include snippets/fastcgi-php.conf;
      #
      #       # With php7.0-cgi alone:
      #       fastcgi_pass 127.0.0.1:9000;
      #       # With php7.0-fpm:
      #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
      #}
      
      # Deny access to. htaccess files if Apache's document root is consistent with nginx
      # deny access to .htaccess files, if Apache's document root
      # concurs with nginx's one
      #
      #location ~ /\.ht {
      #       deny all;
      #}
}

Configure HTTPS service (port 443)

##
# 80 port
##

# Default server, discard requests that lack Host headers
server {
       listen 80;
       return 444;
}

server {
        listen 80;
        listen [::]:80;
        sever_name example.com www.example.com;

        rewrite ^(.*)$ https://$host$ permanent;  port forwarding, 301 redirection
}

##
# 443 port
##
server {
    
    ##
    # Ali Cloud Reference Configuration
    ##
    
    listen 443;
    listen [::]:443;
    server_name example.com www.example.com;
    
    root /var/www/example/;    # Specify the root directory of the document for the virtual server
    index index.html index.htm; # Given URL file
    
    ##
    # Deployment of HTTP Strict Transport Security (HSTS)
    ##
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload;"
    
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    gzip off;
    
    ##
    # SSL configuration
    ##
    
    ssl on;
    ssl_certificate   cert/certfile.pem;    # certificate
    ssl_certificate_key  cert/certfile.key; # private key
    ssl_session_timeout 5m; # Setting timeout time
    # Password suite configuration
    # Cryptographic Suite Name Composition: Key Exchange - Authentication - Encryption Algorithms (Algorithms - Strength - Mode) - MAC or PRF
    ssl_ciphers ECDHE-RSA-AES128-GCM- SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; 
    ssl_protocols TLSv1.2; # Setting the version number of the SSL/TSL protocol
    ssl_prefer_server_ciphers on; # Control the priority of the password suite and let the server choose the algorithm suite to use
    ssl_buffer_size 1400; # Reducing the size of the TLS buffer can significantly reduce the first byte time (HTTPS Authoritative Guide P416)
    
    ##
    # location configuration
    ##
    
    # ...
}

HSTS HTTP Header Standard:

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload;

Parameters:

  • Max-age, the server tells a client that the HSTS standard should be implemented in 31536000 seconds, during which time if the client visits the HTTPS website again, the max-age time will be refreshed.
  • includeSubDomains, the server tells the client that all subdomains under the domain name implement the HSTS standard, which is not only followed by the host issuing the HSTS HTTP header.
  • preload, browser saves websites that need to implement HSTS standard.

ngx_http_limit_conn_module module

http {
    # maximum connection
    # Allocate a shared memory area of 10M in size to limit IP
    # Using the $binary_remote_addr variable, you can reduce the size of each status record to 64 bytes, so that 1 M of memory can hold about 16,000 64 bytes of records.
    limit_conn_zone $binary_remote_addr zone=ips:10m;
    # Allocate a shared memory area of 10M in size to limit the number of server connections
    limit_conn_zone $server_name zone=servers:10m;
    
    # Setting Logging Level
    # When the server rejects or delays processing requests because of high frequency, it can record the corresponding level of logs.
    limit_conn_log_level notice;

    server {
        # Limit access to each IP address by limiting 10 connections
        limit_conn ips 10;
        
        # Maximum number of connections provided by server 1000
        limit_conn servers 1000;
    }
}

ngx_http_limit_req_module module

http {
    # maximum connection
    # Allocate a shared memory area of 10M in size and limit download connections to 1
    limit_conn_zone $binary_remote_addr zone=connections:10m;

    # Maximum concurrency, number of requests per second (r/s), number of requests per minute (r/m)
    # Allocate a memory area with a maximum number of concurrencies, 10M in size, and 1/s of request rate before limit_req limit.
    # Using the $binary_remote_addr variable, you can reduce the size of each status record to 64 bytes, so that 1 M of memory can hold about 16,000 64 bytes of records.
    limit_req_zone $binary_remote_addr zone=requests:10m rate=1r/s;

    # Setting Logging Level
    # When the server rejects or delays processing requests because of high frequency, it can record the corresponding level of logs.
    limit_req_log_level warn;

    # immediately release socket buffer memory on timeout
    reset_timedout_connection on;

    server {
    
        # Only valid for search URL s
        location /search {
            
            # Restriction rate
            # Maximum number of delayed requests is 10, if exceeded, return status code 503
            limit_req zone=requests burst=3 nodelay;
        }
        
        # Limit client bandwidth,
        # Policy: Small files are allowed to download freely, but this restriction is enabled for large files
        location /downloads {
            # First, limit the number of downloaded connections for clients to 1 
            limit_conn connections 1;

            # After downloading 1M content, the limit_rate limit is enabled.
            limit_rate_after 1m;
            
            # Limit the rate of downloading content by client to 500k/s
            limit_rate 500k;
        }
    }
}

Reference resources

Topics: Nginx PHP SSL sudo