As a high-performance web server and reverse proxy server, Nginx is widely favored by website architects. But when using Nginx, we also need to pay attention to security issues, especially when processing URLs.
Due to the flexibility of Nginx, if we do not adopt some URL security strategies, we may be subject to the following attacks:
- SQL injection
- XSS attack
- Illegal file download
- CSRF attack
- Illegal request for access, etc.
This article will introduce the guide for writing Nginx URL security policy.
1. Preconditions
Before writing Nginx URL security policy, you need to master the following knowledge points:
- Regular expression
- Nginx configuration file syntax
- Basic knowledge of HTTP protocol
2. Input filtering
Nginx can use http request header detection to prevent malicious HTTP requests. The specific implementation method is to add a configuration similar to the following to the Nginx configuration file:
if ($http_user_agent ~* "some evil expression") { return 403; }
Or use Nginx’s built-in firewall module for input filtering, as follows:
# block ip sends more than 100 requests per 5 seconds limit_conn_zone $binary_remote_addr zone=one:10m; limit_req_zone $binary_remote_addr zone=two:10m rate=1r/s; server { location / { limit_conn one 10; limit_req zone=two burst=5 nodelay; } }
This example does the following:
- First define two zones, which are memory areas that can store status information. (This also means that if there are many accesses, the cost of this protection may be relatively high)
- If the same IP address sends more than 100 HTTP requests within 5 seconds, then block.
- If the same IP address sends more than 5 HTTP requests within 1 second, it will be blocked.
3. Prevent SQL injection
In actual development, it is necessary to avoid SQL injection. In order to prevent SQL injection attacks, we can configure it as follows:
location ~* (.php|.asp|.ashx)/?$ { if ($args ~* "select.*from") { return 403; } }
This example uses Nginx’s built-in if module to prevent attackers from using select statements to obtain data from the database. If this happens, return 403 Access Forbidden .
4. Prevent XSS attacks
For XSS attacks, we can strengthen the input detection. If a possible XSS attack is detected, the connection can be redirected to a safe URL or an error message can be returned.
if ($args ~* "<script.*>") { return 403; }
This example uses Nginx's built-in if module to detect whether there is content with script tags nested in the URL.
5. Prevent CSRF attacks
When using Nginx, in order to prevent CSRF attacks, you need to prohibit requests from external sites. For example, you can add the following configuration:
location / { if ($http_referer !~ "^https?://$host/") { return 403; } }
This example uses Nginx's built-in if module to limit it to only receiving requests from the $host site. If there are requests from other sites, Nginx will return 403.
6. Prevent file download vulnerabilities
In order to prevent access to improper files, such as private documents, scripts, configuration files, etc., please use the following strategy:
location ~* .(xls|doc|pdf)$ { valid_referers none blocked server_names; if ($invalid_referer) { return 401; } }
This example Using Nginx's built-in valid_referers module, when a request is found to come from an unauthorized site, 401 will be returned.
7. Prohibit access to some URLs
In actual projects, some URLs can be used by attackers, such as admin.php, login.php, etc. We can simply ban their access.
location ~ /(admin|login).php { deny all; }
The configuration of this example prohibits access to URLs ending with admin.php and login.php.
8. Complete example
Finally, based on the above configuration, we can get the following complete example:
server { listen 80; server_name yourdomain.com; # 设置过滤规则 location / { # 禁止非法请求 limit_conn_zone $binary_remote_addr zone=one:10m; limit_req_zone $binary_remote_addr zone=two:10m rate=1r/s; limit_conn one 10; limit_req zone=two burst=5 nodelay; # 防止XSS攻击 if ($args ~* "<script.*>") { return 403; } # 防止SQL注入 if ($args ~* "select.*from") { return 403; } # 禁止admin和login的访问 location ~ /(admin|login).php { deny all; } } # 防止文件下载漏洞 location ~* .(xls|doc|pdf)$ { valid_referers none blocked server_names; if ($invalid_referer) { return 401; } } }
The above is the guide for writing Nginx URL security policy. I hope it can provide some help for your Nginx configuration and improve the security of the system.
The above is the detailed content of Nginx URL security policy writing guide. For more information, please follow other related articles on the PHP Chinese website!

NGINX and Apache are both powerful web servers, each with unique advantages and disadvantages in terms of performance, scalability and efficiency. 1) NGINX performs well when handling static content and reverse proxying, suitable for high concurrency scenarios. 2) Apache performs better when processing dynamic content and is suitable for projects that require rich module support. The selection of a server should be decided based on project requirements and scenarios.

NGINX is suitable for handling high concurrent requests, while Apache is suitable for scenarios where complex configurations and functional extensions are required. 1.NGINX adopts an event-driven, non-blocking architecture, and is suitable for high concurrency environments. 2. Apache adopts process or thread model to provide a rich module ecosystem that is suitable for complex configuration needs.

NGINX can be used to improve website performance, security, and scalability. 1) As a reverse proxy and load balancer, NGINX can optimize back-end services and share traffic. 2) Through event-driven and asynchronous architecture, NGINX efficiently handles high concurrent connections. 3) Configuration files allow flexible definition of rules, such as static file service and load balancing. 4) Optimization suggestions include enabling Gzip compression, using cache and tuning the worker process.

NGINXUnit supports multiple programming languages and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.