Category: Nginx

  • Enable CORS in Nginx

    To enable CORS in nginx, add the following inside web sites server config.

    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

    Restart nginx

    systemctl restart nginx

    See CORS

  • List installed Modules in Nginx

    To list modules compiled with nginx, you can run nginx -V

    nginx -V
    

    This print nginx version along with configuration used to compile nginx.

    nginx version

    If you want just the list of modules, you can use following command

    nginx -V 2>&1 | tr -- - '\n' | grep  _module
    

    Example

    nginx installed modules

    See Nginx

  • Nginx remove html from url

    If you have a static website build using plain html files, your url will look like https://yourdomain/page.html. This .html extension is useful for the files when it is on your local computer, it help computer to associate the file with specific application, say your HTML editor. But on a web server this .html extension serve no purpose. If you are using Nginx web server, you can remove .html extension from your web page urls with following code.

    location / {
        if ($request_uri ~ ^/(.*)\.html$) {
            return 301 /$1;
        }
        try_files $uri $uri.html $uri/ =404;
    }
    

    Remove .php extension

    To remove .php extension, you can use

    location / {
    	try_files $uri $uri.html $uri/ @extensionless-php;
    	index index.html index.htm index.php;
    }
    
    location @extensionless-php {
    	rewrite ^(.*)$ $1.php last;
    }
    

    Reataining Arguments

    To retain arguments, use

    return 301 /$1$is_args$args;
    

    This will redirect /mypage.html?name= to /mypage?name=

    Serve PHP file with .html extension

    See Nginx

  • Nginx show full url in access log

    To show the full URL in the nginx access log, add the following

    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request_method $scheme://$host$request_uri $server_protocol" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" $request_time';

    If you are behind a reverse proxy, replace $remote_addr with $http_x_forwarded_for

    See Nginx

  • Nginx HTTP 414 request-URI too large

    Nginx HTTP 414 request-URI too large

    On a Nginx server, when accessing a long url, i get error

    HTTP 414 Request-URI Too Large
    

    Nginx HTTP 414 request-URI too large

    To fix the error, edit

    vi /etc/nginx/nginx.conf
    

    inside “http” section, find

    large_client_header_buffers
    

    Replace the line with

    large_client_header_buffers 4 32k;
    

    If your URL is very large, you may need to increase the 32k to higher or reduce the url length.

    Large url like this mostly happend due to bad application design, so if possible try to make URL smaller.

    Restart nginx

    systemctl restart nginx
    

    On older servers (centos 6, ubuntu 14, etc..), run

    service nginx restart
    

    See Apache 414 Request-URI Too Long, Nginx

  • Show Real IP Nginx Behind Reverse Proxy

    Show Real IP Nginx Behind Reverse Proxy

    When your Nginx web server is running behind a reverse proxy, you will see IP of the reverse proxy server as visitor IP in web servers access log.

    To fix this, edit nginx.conf file

    vi /etc/nginx/nginx.conf
    

    Find

    http {
    

    Inside http section, add

    set_real_ip_from IP_ADDRESS_OF_PROXY_SERVER_HERE;
    real_ip_header X-Forwarded-For;
    

    Example

    set_real_ip_from 192.168.122.1;
    real_ip_header X-Forwarded-For;
    

    Restart Nginx

    nginx -s reload
    
  • Nginx Location Directive

    Nginx Location Directive is used to route request to correct files.

    Match

    Exact match is used to match an exact URL.

    server {
        listen 80 default_server;
        root /var/www/html;
        index index.html;
        server_name _;
    
        location /ok/ {
            root /home/;
        }
    }
    

    When location is used with no modifiers, then beginning of the URL is matched. In this case, any url http://domain/ok/FILE_NAME will be served from /home/ok/FILE_NAME

    Exact Match (=)

    Exact match is used to match an exact URL.

    server {
        listen 80 default_server;
        root /var/www/html;
        index index.html;
        server_name _;
    
        location = /ok/index.html {
            root /home/;
        }
    }
    

    In this example http://domain/ok/index.html get served from /home/ok/index.html. Only this specific file will be matched.

    Cause Insensitive Regular Expression Match (~*)

    server {
        listen 80 default_server;
        root /var/www/html;
        index index.html;
        server_name _;
    
        location /ok/ {
            root /home/;
        }
    }
    

    Above code routes URL http://domain/ok/ to /home/ok/index.html. But won’t match http://domain/OK/.

    If you need both /ok and /OK work, you need to use

        location ~* /ok/ {
            root /home/;
        }
    

    With this config, http://domain/OK/FILE will be served from /home/OK/FILE.

    See Nginx

  • Nginx Password Protect a website

    Nginx Password Protect a website

    nginx password protect

    To password protect a website, you need to install htpasswd utility. On Ubuntu/Debian, you can install it with the command

    apt install apache2-utils -y

    Now create a password file with the command

    htpasswd -c /etc/nginx/.htpasswd  USER_NAME_HERE

    It will ask for a password.

    Edit the configuration file for your website and add the following in the server entry for the website.

    auth_basic "Members Only";
    auth_basic_user_file /etc/nginx/.htpasswd;

    Restart Nginx.

    systemctl restart nginx

    Now on visiting the website, you will be asked to enter your username and password.

    If you need to allow SSL renewals, then see SSL Renewal On Nginx Password Protected site

    See Nginx

  • Configure Nginx to listen on single IP Address

    By default Nginx listens on all IP address on a server. To make nginx listen on specific IP address, edit nginx configuration file

    vi /etc/nginx/nginx.conf
    

    And VirtualHost/server files for each domain located in folders

    /etc/nginx/conf.d => on CentOS/RHEL
    /etc/nginx/sites-available => on Debian/Ubuntu
    

    Find

    listen 80
    

    Replace with

    listen IP_ADDR_HERE:80
    

    IP_ADDR_HERE = your server IP address on which you need nginx listen on.

    See Nginx

  • Nginx Config for Laravel Application in sub folder

    Nginx Config for Laravel Application in sub folder

    To run Laravel Application on a subfolder of a website, use the following configuration. If you run the Laravel application as the main site, see Nginx Config for Laravel Application

    # subFolderApp1
    
    location /subFolderApp1 {  
        alias /home/yorudomain.com/html/subFolderApp1/public;  
        try_files $uri $uri/ @subFolderApp1;
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_pass unix:/run/php/php7.2-fpm-torrentp.sock;
        }
    }  
    
    location @subFolderApp1 {
        rewrite /subFolderApp1/(.*)$ /subFolderApp1/index.php?/$1 last;
    }
    
    # end subFolderApp1

    Here you place the Laravel application in a subdirectory “subFolderApp1”.

    Example

    server {
        server_name serverok.in www.serverok.in;
        root /home/serverok.in/html/;
        index index.php index.html index.htm;
        client_max_body_size 1000M;
        proxy_read_timeout 600s;
        fastcgi_read_timeout 600s;
        fastcgi_send_timeout 600s;
    
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
    
        # service
    
        location /service {  
            alias /home/serverok.in/html/service/public;  
            try_files $uri $uri/ @nested1;
            location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_param SCRIPT_FILENAME $request_filename;
                fastcgi_pass unix:/run/php/php7.2-fpm-torrentp.sock;
            }
        }  
    
        location @nested1 {
            rewrite /service/(.*)$ /service/index.php?/$1 last;
        }
    
        # end service
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_intercept_errors on;
            fastcgi_buffers 16 16k;
            fastcgi_buffer_size 32k;
            fastcgi_pass unix:/run/php/php7.2-fpm-torrentp.sock;
        }
    
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/serverok.in/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/serverok.in/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    }
    
    server {
        if ($host = www.serverok.in) {
            return 301 https://$host$request_uri;
        } # managed by Certbot
    
        if ($host = serverok.in) {
            return 301 https://$host$request_uri;
        } # managed by Certbot
    
        listen 80;
        server_name serverok.in www.serverok.in;
        return 404; # managed by Certbot
    }

    Back to Nginx

  • Nginx Config for Laravel Application

    Here is Nginx configuration for a laravel application

    server {
        listen 80;
        server_name www.domain.com;
        access_log  /var/log/nginx/domain.com.log;
        root /home/domain.com/html/public;
        index index.html index.php;
        access_log /var/log/nginx/domain.com.log;
        error_log /var/log/nginx/domain.com-error.log;
        client_max_body_size 1000M;
        proxy_read_timeout 600s;
        fastcgi_read_timeout 600s;
        fastcgi_send_timeout 600s;
    
        location / {
            try_files $uri $uri/ /index.php$is_args$args;
        }
    
        location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
           try_files $uri =404;
           access_log off;
           expires max;
        }
    
        location = /robots.txt      { access_log off; log_not_found off; }
        location = /favicon.ico    { access_log off; log_not_found off; }  
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_intercept_errors on;
            fastcgi_buffers 16 16k;
            fastcgi_buffer_size 32k;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
    }
    
    server {
        listen 80;
        server_name  domain.com;
        return       301 http://www.domain.com$request_uri;
    }
    

    Nginx Config for Laravel Application in sub folder

  • Disable TLSv1 in Nginx

    Disable TLSv1 in Nginx

    To disable TLSv1 in nginx, add

    ssl_protocols TLSv1.1 TLSv1.2;
    

    in your server config.

    if you are using letsencrypt SSL, edit file

    vi /etc/letsencrypt/options-ssl-nginx.conf
    

    Find

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    

    Replace with

    ssl_protocols TLSv1.1 TLSv1.2;
    

    Restart Nginx

    service nginx restart
    

    To verify, run

    nmap --script ssl-enum-ciphers -p 443 DOMAIN.EXTN
    

    This will list all supported SSL protocols.

    nmap

    Nginx SSL Configuration

    See Nginx