Linux configuration Nginx service complete detailed version

Table of contents

Preface

Configure Nginx listening port and server block

# Anti-DDoS configuration

# Log configuration

# Set up server block

listening port

Website root directory

default file

Static file directory

Image file directory

# Custom error page

# Reverse proxy configuration

# Configure SSL/TLS

1. Obtain SSL/TLS certificate

2. Install the certificate

3. Configure SSL/TLS

# Configure SSL protocol version and cipher suite

# Configure SSL session cache

# Enable the HSTS header to tell the browser to always use HTTPS

# Prevent clickjacking

# Security header configuration


Preface

When you need to configure an Nginx server to host a website or application, here are some basic steps and sample configurations to get you started. Please note that Nginx configuration can be very flexible and can be customized to your specific needs. The following examples assume you have Nginx installed on your server.

1. Open a terminal and log in to your server.

2. Use a text editor (such as nano or vim ) to open the Nginx configuration file.

The configuration file is usually located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default, but the specific location may vary depending on your operating system. Here is an example using the vim editor:

sudo vim /etc/nginx/nginx.conf

Configure Nginx listening port and server block

In nginx.conf , you can find a block called http , which contains the global configuration of Nginx. You can change the default listening port (default is 80) and add server blocks.

# HTTP模块配置段
http {

  	# 防DDoS配置
    limit_req_zone $binary_remote_addr zone=ddos:10m rate=10r/s;

    # 日志配置
    access_log /var/log/nginx/access.log;
    
    
    # 设置服务器块
    server {

        listen 80; # 监听端口
        
        server_name example.com; # 域名
        
        location / {
            root /var/www/html; # 网站根目录
            index index.html; # 默认文件
        }
        
        location /static/ {
            alias /var/www/static/; # 静态文件目录
        }
        
        location /images/ {
            alias /var/www/images/; # 图像文件目录
        }

        # 自定义错误页面
		    error_page 404 /404.html;
			    location = /404.html {
    		    root /var/www/html;
    		    internal;
		    }
        
        # 反向代理配置
            location /api/ {
                proxy_pass http://backend-server; # 后端服务器地址
            }

        # 配置SSL/TLS
    	    listen 443 ssl;
    	    server_name example.com;
    	    ssl_certificate /path/to/your/certificate.crt;
    	    ssl_certificate_key /path/to/your/private-key.key;

        # 配置SSL协议版本和密码套件
    	    ssl_protocols TLSv1.2 TLSv1.3;
    	    ssl_prefer_server_ciphers off;
    	    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';

  	    # 配置SSL会话缓存
    	    ssl_session_cache shared:SSL:10m;
    	    ssl_session_timeout 10m;

	    # 启用HSTS标头,告诉浏览器始终使用HTTPS
    	    add_header Strict-Transport-Security "max-age=31536000; 
            includeSubDomains; preload";

        # 防止点击劫持
		    add_header X-Frame-Options SAMEORIGIN;

        # 安全头部配置
		    add_header X-Content-Type-Options "nosniff";
		    add_header X-XSS-Protection "1; mode=block";
		    add_header X-Frame-Options "SAMEORIGIN";

    }
}

# Anti-DDoS configuration

limit_req_zone : This is an Nginx directive used to define a request limit zone. This area is used to record request frequency information for each client.

$binary_remote_addr : This is an Nginx variable that represents the client’s IP address. Each different IP address is treated as a separate client.

zone=ddos:10m : This section defines the name of the request restriction zone as "ddos" and allocates 10 megabytes of memory space (10m) to store related data.

rate=10r/s : This section specifies the request rate limit. It means that each IP address is allowed to send up to 10 requests per second (10r/s).

# Log configuration

access_log is an Nginx configuration directive used to define access log settings.

/var/log/nginx/access.log is the path to the log file, which tells Nginx to write the access log to a file named access.log . Usually, Nginx log files are placed in the /var/log/nginx/ directory.

# Set up server block

listening port

A listening port refers to a computer or network device in a computer network that waits for and receives incoming network connections or data flows by specifying a specific network port number. Each network service or application can listen on one or more ports, which are used to identify different network services or communication channels.

Website root directory

The website root directory (also known as the website root folder, website root file directory, or website root directory structure) is the main folder on a web server that contains the files and resources that make up the entire website. This directory is usually the starting point used by web servers to serve website content, and is also the default base path when accessing the website.

default file

When you visit a website, you usually see the website's homepage or default page. This default page is called the index file, and it is the first page of the website shown to visitors.

Static file directory

The static files directory is a folder or directory that contains the static files of the website (files that do not require server-side processing). These static files can include HTML, CSS, JavaScript, images, font files, etc. They do not need to be dynamically generated or processed on the server side, but are provided directly to the client browser.

Image file directory

The image files directory is a folder or directory used to store image files in a website or application. These image files can include various image types such as JPEG, PNG, GIF, SVG, etc. Image file directories are usually used to organize and manage image resources in websites so that they can be displayed on web pages or provided to users through links.

# Custom error page

This configuration tells Nginx to redirect the user to the /404.html page when a 404 error occurs . The root directive in the location block defines the directory where the 404 page is located, here it is /var/www/html . The internal directive is used to limit the location to be processed within Nginx and will not expose the path of this page to the outside.

# Reverse proxy configuration

location /api/ { ... } : This is a location block that specifies that requests for URL paths starting with /api/ should be processed. Only requests that meet this condition will enter this location block for processing.

proxy_pass http://backend-server; : This is the most important part of the configuration block. It specifies the address of the backend server to which Nginx should forward requests.

For example, if the address of your backend server is http://localhost:8000 , then proxy_pass http://localhost:8000; should be written here .

# Configure SSL/TLS

1. Obtain SSL/TLS certificate

First, you need to obtain an SSL/TLS certificate. You can purchase a certificate from an authoritative certificate authority (such as Let's Encrypt, Comodo, DigiCert, etc.) or use a self-signed certificate. Self-signed certificates are suitable for testing and development environments, but in production environments it is recommended to use a certificate issued by a trusted certificate authority to ensure browser and client compatibility.

2. Install the certificate

After you obtain the certificate, you need to install it on the server. Typically, a certificate file includes a public key file (usually with a .crt or .pem extension) and a private key file (usually with a .key extension). Store these files in a secure location on the server.

3. Configure SSL/TLS

In the configuration file, find the section related to SSL/TLS. In Nginx, SSL is usually configured within the server block.

server { ... } : This is an Nginx server block that defines the configuration of the server.

listen 443 ssl; : This line specifies that the server listens on port 443 and enables SSL encryption. All incoming HTTPS requests will be handled on this port.

server_name example.com; : This defines the domain name of the server.

ssl_certificate /path/to/your/certificate.crt; This line specifies the path to the SSL certificate used to encrypt transmitted data.

ssl_certificate_key /path/to/your/private-key.key; : This line specifies the path to the SSL private key file used to decrypt incoming encrypted data.

# Configure SSL protocol version and cipher suite

Configuring the SSL protocol version and cipher suite usually does not need to be changed to your own, because this part of the configuration is optimized for the security and performance of the server.

ssl_protocols specifies the supported TLS versions, generally TLSv1.2 and TLSv1.3 are safe choices and do not need to be changed unless you have specific needs.

ssl_prefer_server_ciphers is set to off to ensure that Nginx does not enforce the order of server-side cipher suites, and usually does not need to be changed.

ssl_ciphers defines supported cipher suites, using ECDHE (Elliptic Curve Diffie-Hellman Ephemeral) key exchange and AES-GCM modes, and usually does not need to be changed.

# Configure SSL session cache

These two lines of configuration are settings for configuring the SSL session cache. They are very important for improving the SSL/TLS performance of the server. Let me explain what they mean:

ssl_session_cache shared:SSL:10m;: This line of configuration specifies the type, name and size of the SSL session cache.

10m : This part specifies the size of the session cache. In the example, the cache size is set to 10 megabytes (MB). This means that the server can store approximately 10 megabytes of SSL session data.

ssl_session_timeout 10m;: This line of configuration specifies the timeout period for the SSL session in the cache.

10m : This part specifies the session timeout, which corresponds to the cache size above. In the example, the session will expire after 10 minutes and be removed from the cache.

# Enable the HSTS header to tell the browser to always use HTTPS

max-age=31536000 : Specifies the duration of the HSTS policy in seconds. Here, max-age is set to 31536000 seconds, which is equal to one year. This means that once a browser receives this HSTS header, it will remember your site for one year and force access using an HTTPS connection.

# Prevent clickjacking

The purpose of this configuration is to enhance the security of your website and prevent clickjacking attacks, in which attackers embed your web pages within their malicious website in order to deceive users. By setting X-Frame-Options to SAMEORIGIN , you tell the browser to only allow your web pages to be nested within the same origin, thus improving the security of your site

# Security header configuration

1、X-Content-Type-Options "nosniff"

The X-Content-Type-Options header is used to control whether the browser should perform MIME type sniffing.

The "nosniff" directive tells the browser not to perform sniffing. Even if the response returned by the server contains inconsistent MIME type information, the browser will not try to guess the content type of the response.

This helps prevent MIME type confusion attacks, where an attacker could inject malicious content into the response and rely on the browser to incorrectly interpret the response's MIME type.

2、X-XSS-Protection "1; mode=block"

The X-XSS-Protection header is used to enable the browser's built-in cross-site scripting (XSS) filter.

The "1; mode=block" directive enables the XSS filter and sets the page to block loading if a potential XSS attack is detected.

This helps prevent XSS attacks, where attackers try to inject malicious scripts into web pages to perform malicious actions, such as stealing user information or hijacking user sessions.

3、X-Frame-Options "SAMEORIGIN"

The X-Frame-Options header is used to control whether web pages are allowed to be embedded in <iframe> .

The "SAMEORIGIN" directive indicates that only web pages with the same domain name as the original web page are allowed to be nested in <iframe> .

This helps prevent clickjacking attacks, in which an attacker might try to embed your site within a malicious site to trick users into taking action or steal information.

Guess you like

Origin blog.csdn.net/m0_67906358/article/details/132987458