Operations 27 min read

Master Nginx Rewrite, Anti-Hotlinking, and Keepalived HA

This guide explains Nginx rewrite syntax and flags, provides practical rewrite examples, demonstrates how to configure anti‑hotlinking, outlines static‑dynamic resource separation with caching, and shows step‑by‑step installation and configuration of Keepalived for high‑availability Nginx clusters, including required scripts and host settings.

Programmer DD
Programmer DD
Programmer DD
Master Nginx Rewrite, Anti-Hotlinking, and Keepalived HA

Nginx Rewrite Rules

1. Nginx rewrite syntax

The rewrite rule rewrites a URL to another URL, similar to a redirect, often used for aesthetic URLs or SEO friendliness.

Syntax:

rewrite [flag];

The flag can be:

last – equivalent to Apache's (L) flag, ends rewrite processing.

break – stops further rule processing after this rule matches.

redirect – returns a 302 temporary redirect.

permanent – returns a 301 permanent redirect.

last and break keep the browser URL unchanged while rewriting internally.

2. Nginx rewrite examples

a) Redirect www.dbspread.com to www.dbspread.com/new.index.html:

server {
    listen 80;
    server_name www.dbspread.com;
    index index.jsp index.html index.htm;
    root /usr/local/nginx/html;
    location / {
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        rewrite ^/$ http://www.dbspread.com/new.index.html permanent;
        proxy_pass http://web1;
    }
    rewrite ^/$ http://www.dbspread.com/new.index.html permanent;
}

The rewrite line follows the syntax rewrite <regex> <replacement> [flag]; Regular expression symbols:

* – matches zero or more of the preceding character
+ – matches one or more of the preceding character
? – matches zero or one of the preceding character
^ – start of string
$ – end of string
. – wildcard for any character

b) Redirect multiple domains to a single domain:

server {
    listen 80;
    server_name www.dbspread.com;
    index index.jsp index.html index.htm;
    root /usr/local/nginx/html;
    if ($host != 'www.dbspread.com') {
        rewrite ^/(.*)$ http://www.dbspread.com/$1 permanent;
    }
}

Nginx Anti‑Hotlinking

1. What is anti‑hotlinking?

When a video URL such as http://www.dbspread.com/download/av123.rmvb is referenced from another site (e.g., www.test.com), it is considered hotlinking. Anti‑hotlinking prevents this.

2. Implementation

server {
    listen 80;
    server_name www.dbspread.com *.dbspread.com;
    location ~* \.(rmvb|jpg|png|swf|flv)$ {
        valid_referers none blocked www.dbspread.com;
        root html/b;
        if ($invalid_referer) {
            return 403;
        }
    }
}

Nginx Static/Dynamic Separation

1. Concept

Static/dynamic separation distinguishes immutable resources from frequently changing ones, allowing static assets to be cached for improved performance.

2. Architecture diagram

3. Implementation steps

4.1 Create a static CSS file

body {
    margin: 10px 20px;
    text-align: center;
    font-family: Arial, sans-serif;
    background-color: red;
}

4.2 Place the file in a static directory

4.3 Reference the CSS in the web application

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="http://www.static.com/button.css" />
    <meta charset="utf-8">
    <title>test</title>
  </head>
  <body>
    欢迎来到8080端口tomcat
  </body>
</html>

4.4 Nginx configuration for static separation

server {
    listen 80;
    server_name www.dbspread.com;
    index index.jsp index.html index.htm;
    root /usr/local/nginx/html;
    if ($host != 'www.dbspread.com') {
        rewrite ^/(.*)$ http://www.dbspread.com/$1 permanent;
    }
    location ~* \.(rmvb|jpg|png|swf|flv)$ {
        valid_referers none blocked www.dbspread.com;
        root html/b;
        if ($invalid_referer) { return 403; }
    }
    location / {
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://web1;
    }
    location ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
        root /var/local/static;
        expires 30d;
    }
    access_log /usr/local/logs/web2/access.log main;
    error_log /usr/local/logs/web2/error.log crit;
}

Nginx + Keepalived High Availability

1. What is Keepalived?

Keepalived was originally designed for LVS load‑balancing health checks and later added VRRP support, enabling high‑availability for services such as Nginx, HAProxy, MySQL, etc.

2. Main functions

Manage LVS load‑balancing software.

Health‑check LVS cluster nodes.

Provide failover for network services.

3. Failover mechanism

The master node sends VRRP heartbeats; if they stop, the backup node takes over the virtual IP and services. When the master recovers, the backup releases the IP.

4. Architecture diagram

Virtual IP (VIP): 192.168.152.200 – external service address.

Master node: 192.168.152.130 (nginx + keepalived)

Backup node: 192.168.152.129 (nginx + keepalived)

5. Installation steps

Environment: CentOS 6, JDK.

wget www.keepalived.org/software/keepalived-1.3.5.tar.gz
tar -zxvf keepalived-1.3.5.tar.gz
cd keepalived-1.3.5
./configure --prefix=/usr/local/keepalived
# install required libraries if prompted
make && make install

Create configuration directory and copy the sample config:

mkdir /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived

5.2 Master node configuration (/etc/keepalived/keepalived.conf)

global_defs {
    notification_email { [email protected] }
    notification_email_from [email protected]
    smtp_server smtp.hysec.com
    smtp_connection_timeout 30
    router_id nginx_master
}

vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 66
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script { chk_http_port }
    virtual_ipaddress { 192.168.152.200 }
}

5.3 Backup node configuration (similar, state BACKUP, priority 99, router_id nginx_backup)

global_defs {
    notification_email { [email protected] }
    notification_email_from [email protected]
    smtp_server smtp.hysec.com
    smtp_connection_timeout 30
    router_id nginx_backup
}

vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 66
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script { chk_http_port }
    virtual_ipaddress { 192.168.152.200 }
}

5.4 Script to check Nginx status

#!/bin/bash
# Detect if Nginx is running
A=$(ps -C nginx --no-header | wc -l)
if [ $A -eq 0 ]; then
    /usr/local/nginx/sbin/nginx
    if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
        killall keepalived
    fi
fi

5.5 Nginx configuration (common for both nodes)

user root root;
worker_processes 4;
worker_cpu_affinity 00000001 00000010 00000100 00001000;
worker_rlimit_nofile 102400;

events {
    use epoll;
    worker_connections 102400;
    multi_accept on;
}

http {
    include mime.types;
    default_type application/octet-stream;
    charset utf-8;
    server_names_hash_bucket_size 128;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 32k;
    client_max_body_size 300m;
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;
    proxy_connect_timeout 5;
    proxy_read_timeout 60;
    proxy_send_timeout 5;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    upstream web1 {
        server 192.168.152.129:8080 weight=1 max_fails=2 fail_timeout=30s;
        server 192.168.152.129:8081 weight=1 max_fails=2 fail_timeout=30s;
    }

    server {
        listen 80;
        server_name www.dbspread.com;
        index index.jsp index.html index.htm;
        root /usr/local/nginx/html;
        if ($host != 'www.dbspread.com') {
            rewrite ^/(.*)$ http://www.dbspread.com/$1 permanent;
        }
        location ~* \.(rmvb|jpg|png|swf|flv)$ {
            valid_referers none blocked www.dbspread.com;
            root html/b;
            if ($invalid_referer) { return 403; }
        }
        location / {
            proxy_next_upstream http_502 http_504 error timeout invalid_header;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://web1;
        }
        location ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
            root /var/local/static;
            expires 30d;
        }
        access_log /usr/local/logs/web2/access.log main;
        error_log /usr/local/logs/web2/error.log crit;
    }
}

After configuring both nodes, start Keepalived with /usr/local/keepalived/sbin/keepalived. The master node will hold the virtual IP; if it fails, the backup automatically takes over, and when the master returns, it regains the IP.

Testing the setup by accessing www.dbspread.com shows normal service, and stopping the master node demonstrates seamless failover to the backup.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

high availabilitystatic assetskeepalivedrewriteanti-hotlinking
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.