Environment Setup and Nginx Compilation
Begin by installing the necessary compiler and development libraries required for Nginx to function properly, including support for SSL and regular expressions.
yum install -y gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel
Extract the source archive and navigate into the directory. Execute the configuration script to enable specific modules such as the status monitor and SSL support.
tar -zxvf nginx-1.18.0.tar.gz -C /usr/local/src/
cd /usr/local/src/nginx-1.18.0
./configure --with-http_ssl_module --with-http_stub_status_module
make && make install
Configuring Nginx as a System Service
To ensure the web server starts automatically on boot, create a systemd service unit file instead of modifying rc.local.
cat > /usr/lib/systemd/system/nginx.service <<'EOF'
[Unit]
Description=The Nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable nginx
systemctl start nginx
Configuring Backend Load Balancing
For the backend services, prepare multiple application instances. Define an upstream block in the Nginx configuration to distribute traffic among these servers.
upstream java_backend_cluster {
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:8081 weight=1;
}
Ensure the firewall allows traffic to the application ports.
firewall-cmd --permanent --add-port={80/tcp,8080/tcp,8081/tcp}
firewall-cmd --reload
Deploying the Frontend and Configuring Reverse Proxy
Copy the built static assets (e.g., from a Vue.js or React build) to the designated web root. Configure the server block to serve the frontend and proxy API requests to the backend cluster.
worker_processes auto;
events {
worker_connections 2048;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream java_backend_cluster {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server {
listen 80;
server_name app.example.com;
root /var/www/html/dist;
location / {
try_files $uri $uri/ /index.html;
}
location /service/ {
proxy_pass http://java_backend_cluster/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
After saving the configuration, verify the syntax and reload the service to apply changes.
/usr/local/nginx/sbin/nginx -t
systemctl reload nginx