Tag: nginx

  • Install Nginx ModSecurity on CentOS 7

    Install Nginx ModSecurity on CentOS 7

    ModSecurity is a Web Application Firewall that protects your website from hacking attacks. It is Open Source and free to use. It can be used with webservers like Apache, Nginx, and IIS. To install ModSecurity with Nginx, we need to compile the ModSecurity Nginx module and activate it in the Nginx configuration file.

    Install the compilers and libraries needed for building the source code.

    yum groupinstall "Development Tools"
    

    Install dependency

    yum install bison curl curl-devel doxygen flex gcc-c++ git GeoIP-devel libxml2 libxml2-devel lmdb lmdb-devel lua lua-devel pcre-devel ssdeep ssdeep-devel yajl yajl-devel zlib-devel
    

    Download and install ModSecurity

    cd /usr/local/src/
    git clone --depth 1 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity
    cd ModSecurity/
    git submodule init
    git submodule update
    ./build.sh
    ./configure
    make
    make install
    

    Clone ModSecurity-nginx repository. This contains Nginx ModSecurity module source code.

    cd /usr/local/src
    git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.git
    

    We need to download the source code for the version of Nginx you are running now. For this, check Nginx version with the command

    [root@ok ~]# nginx -v
    nginx version: nginx/1.20.1
    [root@ok ~]#
    

    In this case, we use Nginx 1.20.1, go to http://nginx.org/en/download.html and download the source code for Nginx version you are using.

    cd /usr/local/src
    wget http://nginx.org/download/nginx-1.20.1.tar.gz
    tar xvf nginx-1.20.1.tar.gz
    cd nginx-1.20.1
    

    Find out the configure command used to compile nginx.

    [root@ok ~]# nginx -V
    nginx version: nginx/1.20.1
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
    built with OpenSSL 1.0.2k-fips  26 Jan 2017
    TLS SNI support enabled
    configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
    [root@ok ~]# 
    

    You can see configure arguments on the last line, we need to use these arguments when we compile Nginx from source code.

    Run

    cd /usr/local/src/nginx-1.20.1
    ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --add-dynamic-module=../ModSecurity-nginx
    

    In the above, we added –add-dynamic-module=../ModSecurity-nginx at end of the configure command to compile the Nginx module.

    To build Nginx modules, run

    make modules
    

    Once the module is built, copy it to /etc/nginx/modules

    cp objs/ngx_http_modsecurity_module.so /etc/nginx/modules
    

    Copy ModSecurity configuration files

    cp /usr/local/src/ModSecurity/modsecurity.conf-recommended /etc/nginx/modsecurity.conf
    cp /usr/local/src/ModSecurity/unicode.mapping /etc/nginx/unicode.mapping
    

    Enable ModSecurity

    sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/g' /etc/nginx/modsecurity.conf
    

    To load ModSecurity module, edit file

    vi /etc/nginx/nginx.conf
    

    Find

    worker_processes  auto;
    

    Add below

    load_module modules/ngx_http_modsecurity_module.so;
    

    Edit your server config (virtual host entry), add

    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsecurity.conf;
    

    Install ModSecurity Rules

    You can download ModSecurity rules from

    https://coreruleset.org

    At the time of writing this, the latest version is v3.3.2. So let’s download and install it.

    cd /usr/local/src
    wget https://github.com/coreruleset/coreruleset/archive/refs/tags/v3.3.4.tar.gz
    tar xvf v3.3.4.tar.gz
    mv coreruleset-3.3.4 /etc/nginx
    cd /etc/nginx/coreruleset-3.3.4
    cp crs-setup.conf.example crs-setup.conf
    

    To activate the rule, edit the file

    vi /etc/nginx/modsecurity.conf
    

    At end of the file, add

    Include /etc/nginx/coreruleset-3.3.4/crs-setup.conf
    Include /etc/nginx/coreruleset-3.3.4/rules/*.conf
    SecRule ARGS:sec-test "@contains hacker" "id:1234,deny,status:403"
    

    Restart Nginx

    systemctl restart nginx
    

    To verify ModSecurity is working, access your website URL with

    curl -I http://YOUR-SERVER-IP-OR-DOMAIN/?sec-test=hacker
    

    You will see 403 Forbidden error.

    boby@sok-01:~$ curl -I http://152.167.4.94?sec-test=hacker
    HTTP/1.1 403 Forbidden
    Server: nginx/1.20.1
    Date: Mon, 12 Jul 2021 18:24:36 GMT
    Content-Type: text/html
    Content-Length: 153
    Connection: keep-alive
    
    boby@sok-01:~$ 
    

    See ModSecurity Web Application Firewall, Nginx

  • How to fix WordPress 404 error in Webuzo

    How to fix WordPress 404 error in Webuzo

    Webuzo hosting control panel has the option for selecting web servers Apache or Nginx. On a server using Nginx, after uploading the WordPress site and restoring the database, the website home page worked. When I clicked on any web page, I get a 404 Page not found error.

    To fix this, you need to add an extra configuration for Nginx. Login to Webuzo control panel.

    Webuzo Extra configuration

    Click on Extra Configuration.

    webuzo

    On this page, select the domain name that you need 404 error fixed. On Webservers dropdown select Nginx.

    Create a file permlink.conf on your computer with the following content

    try_files $uri $uri/ /index.php?$args;
    

    Browse and upload this file in the Webuzo control panel. This will fix the 404 error for the WordPress site.

    Webuzo will create a configuration file at

    /usr/local/apps/nginx/etc/conf.d/YOUR-DOMAIN.TLD/permlink.conf
    
  • Enable SSL for icecast steam using nginx

    On ubuntu server running icecast, when i try enable SSL as per CentovaCast Enable SSL on icecast, i get following error

    connection/get_ssl_certificate No SSL capability
    

    I don’t compile my own icecast installation as it use Ubunu version of icecast, that get updated using apt.

    Instead of getting icecast serve steam using SSL, i installed Nginx, and proxy traffic from SSL port to icecast.

    Install nginx with

    apt install nginx
    

    remove default server entry

    rm -f /etc/nginx/sites-enabled/default
    

    Create file

    vi /etc/nginx/sites-enabled/stream.comf
    

    Add

    server {
        listen       9000 ssl;
        server_name  icecast.serverok.in;
        root         /var/www/html;
        ssl_certificate /etc/letsencrypt/live/icecast.serverok.in/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/icecast.serverok.in/privkey.pem;
    
        client_max_body_size 100M;
        proxy_read_timeout 600s;
        proxy_buffer_size   128k;
        proxy_buffers   4 256k;
        proxy_busy_buffers_size   256k;
    
        location / {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:8000;
        }
    }
    

    In above configuration

        ssl_certificate /etc/letsencrypt/live/icecast.serverok.in/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/icecast.serverok.in/privkey.pem;
    

    is the SSL i already have on server. Replace it with path to SSL certifciate on your server. If you don’t have an SSL, you need to purcahse one or get a free SSL using LetsEncrypt.

    Restart Nginx

    systemctl restart nginx
    

    Now stream on port 8000 will work using HTTPS on port 9000.

    Modify ports as required.

    If you use Free LetsEncrypt SSL, you may need to add a cronjob to auto reastart nginx when SSL get updated.

    crontab -e
    

    Add

    @weekly systemctl restart nginx
    

    See Icecast, Nginx

  • Nginx Hotlink Protection

    To block hotlink protection or bandwidth stealing, you can add the following to the server configuration of your website.

    valid_referers yourdomain.tld www.yourdomain.tld;
    
    if ($invalid_referer) {
        return 403;
    }

    If you need to allow hotlinks from a specific domain, you can edit the valid_referers line and add the URL. For allowing access without any referral, you can use “none” instead of the domain name. For example

    valid_referers none yourdomain.tld www.yourdomain.tld;

    If you only want to limit access to images and videos, you can put the above code in a location block like

    location ~* \.(mp4|gif|png|jpg|jpeg|css|ico)$ {
        valid_referers  yourdomain.tld www.yourdomain.tld;
        if ($invalid_referer) {
           return 403;
        }
    }

    Example

    https://gist.github.com/serverok/e7e8e275a7ec3b69e19252edfed483e2

    See Nginx

  • Nginx Proxy Manager Certificate Key is not valid

    Nginx Proxy Manager Certificate Key is not valid

    When adding custom SSL on Nginx Proxy Manager, i get following error.

    Upload failed: Certificate Key is not valid (Command failed: openssl ec -in /tmp/15dbf072-4022-aee94-0f88e4fb8d86/tmp -check -noout 2>&1 )

    Nginx Proxy Manager Custom SSL upload error

    I tried upgrading Nginx Proxy Manager to the latest version with the following commands

    cd ~/nginx-proxy-manager/
    docker compose down
    docker compose pull
    docker compose up -d

    Even after the upgrade, this error persists.

    I checked logs for the docker container, but there were no errors.

    docker logs -f nginx-proxy-manager_app_1
    

    To fix this error, I edited the SSL key file.

    Find

    -----BEGIN PRIVATE KEY-----

    Replace with

    -----BEGIN RSA PRIVATE KEY-----

    Find

    -----END PRIVATE KEY-----

    Replace with

    -----END RSA PRIVATE KEY-----

    Now close the SSL upload dialogue and start over the custom SSL upload process. It will work.

    See Nginx Proxy Manager

  • How to block .git directory in nginx

    When using git version control to deploy application, many forget to secure .git folder. This allows anyone to clone your git repository. If you have any credentials commited to your git version control, then hacker will be able to gain access.

    To avoid this, it is better plan the git repo in a way you have .git folder outside of your document root. If this is not possible, you need to block access to .git folder using nginx configuration.

    To block access to .git folder, add following to your nginx server entry.

    location ~ /\.git {
      deny all;
    }
    

    Now restart nginx

    systemctl restart nginx
    

    See Nginx, git

  • Nginx on Windows

    You can download nginx for windows from

    https://nginx.org/en/download.html

    To download nginx from command line, use following command in PowerShell

    Invoke-WebRequest -Uri https://nginx.org/download/nginx-1.19.6.zip -OutFile nginx-1.19.6.zip
    

    Auto Start Nginx on Windows

    When using Nginx on Windows, you need to escape paths with \ like following

    root C:\\sites\\my-site;
    

    For SSL, i used

    listen 443 ssl http2;
    ssl_certificate C:\\nginx\\ssl\\crt\\dedi.ai-chain.pem;
    ssl_certificate_key C:\\nginx\\ssl\\crt\\dedi.ai-key.pem;
    

    See Nginx

  • Enable Nginx Status Page

    Nginx status is provided by http_stub_status module. To verify if your Nginx is installed with this module, run

    nginx -V 2>&1 | grep -o with-http_stub_status_module
    

    If the result shows “with-http_stub_status_module”, you have the module installed.

    nginx status module

    To enbale stats edit nginx configuration file for your web site, add following code

    location /nginx_status {
        stub_status;
    }
    

    To linmit access to this page, you can use allow

    location /nginx_status {
     	stub_status;
     	allow 127.0.0.1;
     	allow YOUR_IP_HERE;
     	deny all;
    }
    

    Replace YOUR_IP_HERE with your actial IP address.

    Restart nginx with

    systemctl restart nginx
    

    Now you should be able to see nginx server stats at url

    https//yourdomain.com/nginx_status

    nginx status

    See Nginx

  • Nginx upstream sent too big header

    Nginx upstream sent too big header

    When I log in to a PrestaShop website, I get an error on a Plesk server.

    502 Bad Gateway
    

    On checking error login for the site in folder /var/www/vhosts/domain.com/logs/proxy_error_log, I found the following error message

    proxy_error_log:2020/11/25 19:41:41 [error] 1809#0: *39664 upstream sent too big header while reading response header from upstream, client: 59.92.71.53, server: tulivesi.com, request: “POST /en/login?back=my-account HTTP/2.0”, upstream: “https://shop.serverok.in:7081/en/login?back=my-account”, host: “shop.serverok.in”, referrer: “https://shop.serverok.in/en/login?back=my-account”

    To fix, add the following to Nginx config.

    If Nginx works as a reverse proxy to another application server.

    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    

    If Nginx serve pages using FastCGI/fpm.

    fastcgi_buffers 16 16k; 
    fastcgi_buffer_size 32k;
    

    On Plesk Server

    On Plesk, go to the domain name, then click “Apache & nginx Settings”. On next page add the following code and click OK.

    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    

    Plesk Nginx

    See Nginx

  • Country Blocking with nginx GeoIP on Ubuntu/Debian

    On Ubuntu/Debian, install nginx geoip module with

    apt install geoip-database libgeoip1 libnginx-mod-http-geoip -y
    

    Now edit nginx.conf

    vi /etc/nginx/nginx.conf
    

    Find

    http {
    

    Add below

    geoip_country /usr/share/GeoIP/GeoIP.dat;
    map $geoip_country_code $my_country_blocker {
        default no;
        US yes;
        AU yes;
        CA yes;
    }
    

    nginx geoip

    You can add 2 letter country code and set ye/no as required.

    To implement GeoIP blocking for a web site, you need to edit server entry for the web site. In this cause, i will use the default web site.

    vi /etc/nginx/sites-enabled/default
    

    Find

    server {
    

    Add blow

    if ($my_country_blocker = no) {
        return 444;
    }
    

    nginx geoip server configuration

    This will block access to the web site from any country that is not listed in nginx.conf

    You need to restart nginx web server

    systemctl restart nginx
    

    If you need to redirect blocked users to another site, use

    if ($my_country_blocker = no) {
        rewrite ^ https://google.com break;
    }
    

    This will redirect the visitor to google if their country is not US, AU or CA.

    See Nginx

  • Nginx Commands

    Nginx Commands

    Start Nginx

    nginx
    

    Stop Nginx

    nginx -s stop
    

    Reload Nginx

    nginx -s reload
    

    Test Nginx configuration

    nginx -t
    

    See Nginx