Nginx Basic Commands and Examples

Linux version used: Amazon Linux 2023

Common Nginx-related Commands

# Start Nginx as a service
sudo systemctl start nginx

# Check the status of Nginx
sudo systemctl status nginx

# Restart Nginx service
sudo systemctl restart nginx

# Reload Nginx with new configuration
sudo systemctl reload nginx

# Stop Nginx service
sudo systemctl stop nginx

# Make Nginx automatically start when booting
sudo systemctl enable nginx

# Check the syntax of configuration files
sudo nginx -t

Notes:

The reload will automatically check the syntax of configuration files. If there are errors, the current service will be maintained.

Configuration Files

Here is a simple example of configuration files:

# File: /etc/nginx/nginx.conf

# ...

http {
    # ...

    include /etc/nginx/servers/*.conf;
}
# File: /etc/nginx/servers/websitea.conf

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;

    include /etc/nginx/servers/ssl/websitea.ssl.conf;

    server_name websitea.com www.websitea.com;

    location / {
        # This can be used for simple static websites

        root /path/to/website/files;
        index index.html;
    }

    location /api {
        # Suppose an api service is running at port 1145

        # Get rid of the /api part
        rewrite ^/api/(.*)$ /$1 break;

        proxy_pass http://localhost:1145;
        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_set_header	X-Forwarded-Proto $scheme;
    }
}
# File: /etc/nginx/servers/ssl/websitea.ssl.conf

ssl_certificate "/path/to/crt";
ssl_certificate_key "/path/to/key";
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers PROFILE=SYSTEM;
ssl_prefer_server_ciphers on;