As we all know, Nginx is a good alternative to Apache service. It is characterized by less memory and strong concurrency. In fact, the concurrency of Nginx performs better in the same type of web server, so well-known domestic manufacturers such as Taobao, Jingdong, Baidu, Sina, Netease, Tencent, etc. Both are using the Nginx website.
Introduction to Nginx
Nginx is an open source, high-performance, highly reliable Web and reverse proxy server, and supports hot deployment. It also provides IMAP/POP3/SMTP services, which can run uninterruptedly and provide hot update functions. It occupies less memory and has strong concurrency. The most important thing is that Nginx is free and can be commercialized, and the configuration and use are relatively simple.
Nginx features
- High concurrency, high performance
- Modular architecture makes it very scalable
- The asynchronous non-blocking event-driven model is similar to Node.js
- Uninterrupted operation without restart
- Hot deployment, smooth upgrade
- Fully open source, good ecology
The most important usage scenarios of Nginx:
- Static resource service
- Reverse proxy services, including caching, load balancing, etc.
- API service, OpenResty
Therefore, today, the migrant worker will put together a Nginx for everyone to learn and use for production configuration reference. It mainly includes the following three aspects:
- Basic configuration
- Advanced configuration
- Security configuration
Basic configuration
Remove unused Nginx modules
./configure --without-module1 --without-module2 --without-module3例如:./configure --without-http_dav_module --withouthttp_spdy_module#注意事项:配置指令是由模块提供的。确保你禁用的模块不包含你需要使用的指令!在决定禁用模块之前,应该检查Nginx文档中每个模块可用的指令列表。
Smooth upgrade and rollback of Nginx version
Get a smooth upgrade and rollback of the Nginx version in 1 minute
Process-related configuration
worker_processes 8;#Nginx 进程数,建议按照CPU数目来指定,一般为它的倍数 (如,2个四核的CPU计为8)。worker_rlimit_nofile 65535; #一个Nginx 进程打开的最多文件描述符数目worker_connections 65535;#每个进程允许的最多连接数
Listening port
server {
listen 80; #监听端口
server_name www.mingongge.com; #域名信息
location / {
root /www/www; #网站根目录
index index.html index.htm; #默认首页类型
deny 192.168.2.11; #禁止访问的ip地址,可以为all
allow 192.168.3.44; #允许访问的ip地址,可以为all
}
}
Tips to add: four ways to write domain name matching
精确匹配:server_name www.mingongge.com ;
左侧通配:server_name *.mingongge.com ;
右侧统配:server_name www.mingongge.* ;
正则匹配:server_name ~^www\.mingongge\.*$ ;
匹配优先级:精确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配
Configure Nginx status page
[root@proxy ~]# cat /usr/local/nginx/conf/nginx.conf
… …
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
}
… …
[root@proxy ~]# /usr/local/nginx/sbin/nginx -s reload
Nginx log (access and error log management)
error_log /var/log/nginx/error.log warn;
#配置错误日志的级别及存储目录
events {
worker_connections 1024;
}
http {
..................
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#配置日志的模式
access_log /var/log/nginx/access.log main;
#配置访问日志存储目录
}
The above configuration is only the basic configuration of Nginx itself about logs. In the actual production environment, we need to collect logs and analyze logs to determine the problem better. Recommend to everyone: super dry goods! through several methods such as filebeat, logstash, and rsyslog
http related configuration
http {
sendfile on #高效传输文件的模式 一定要开启
keepalive_timeout 65 #客户端服务端请求超时时间
}
Static resource configuration
server {
listen 80;
server_name mingongge.com;
location /static {
root /wwww/web/web_static_site;
}
}
You can also use the following method
location /image {
alias /web/nginx/static/image/;
}
注意:使用alias末尾一定要添加/,并且它只能位于location中
Reverse proxy
For example, if there are different projects in the production environment (in the same service), this is more practical. Use a reverse proxy to request forwarding.
http {
.............
upstream product_server{
127.0.0.1:8081;
}
upstream admin_server{
127.0.0.1:8082;
}
upstream test_server{
127.0.0.1:8083;
}
server {
#默认指向product的server
location / {
proxy_pass http://product_server;
}
location /product/{
proxy_pass http://product_server;
}
location /admin/ {
proxy_pass http://admin_server;
}
location /test/ {
proxy_pass http://test_server;
}
}
}
More about Nginx practice: location path matching
Load balancing
upstream server_pools {
server 192.168.1.11:8880 weight=5;
server 192.168.1.12:9990 weight=1;
server 192.168.1.13:8989 weight=6;
#weigth参数表示权值,权值越高被分配到的几率越大
}
server {
listen 80;
server_name mingongge.com;
location / {
proxy_pass http://server_pools;
}
}
Other proxy-related configurations
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k; #设定缓存文件夹大小
proxy_set_header Host $host;
proxy_set_header X-Forwarder-For $remote_addr; #获取客户端真实IP
Advanced configuration
Redirect configuration
location / {
return 404; #直接返回状态码
}
location / {
return 404 "pages not found";
#返回状态码 + 一段文本
}
location / {
return 302 /blog ;
#返回状态码 + 重定向地址}
location / {
return https://www.mingongge.com ;
#返回重定向地址
}
The example is as follows
server {
listen 80;
server_name www.mingongge.com;
return 301 http://mingongge.com$request_uri;
}
server {
listen 80;
server_name www.mingongge.com;
location /cn-url {
return 301 http://mingongge.com.cn;
}
}
server{
listen 80;
server_name mingongge.com; # 要在本地hosts文件进行配置
root html;
location /search {
rewrite ^/(.*) https://www.mingongge.com redirect;
}
location /images {
rewrite /images/(.*) /pics/$1;
}
location /pics {
rewrite /pics/(.*) /photos/$1;
}
location /photos {
}
}
Set the upper limit of buffer capacity
This setting can prevent buffer overflow attacks (also the Server module)
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
#设置后,不管多少HTTP请求都不会使服务器系统的缓冲区溢出了
Limit the maximum number of connections
Configure limit_conn_zone in the http module and outside the server module, configure the connected IP, configure limit_conn in the http, server or location module, and configure the maximum number of IP connections.
limit_conn_zone $binary_remote_addr zone=addr:5m;
limit_conn addr 1;
Gzip compression
gzip_types
#压缩的文件类型
text/plain text/css
application/json
application/x-javascript
text/xml application/xml
application/xml+rss
text/javascript
gzip on;
#采用gzip压缩的形式发送数据
gzip_disable "msie6"
#为指定的客户端禁用gzip功能
gzip_static;
#压缩前查找是否有预先gzip处理过的资源
gzip_proxied any;
#允许或者禁止压缩基于请求和响应的响应流
gzip_min_length 1000;
#设置对数据启用压缩的最少字节数
gzip_comp_level 6;
#设置数据的压缩等级
Cache configuration
open_file_cache
#指定缓存最大数目以及缓存的时间
open_file_cache_valid
#在open_file_cache中指定检测正确信息的间隔时间
open_file_cache_min_uses
#定义了open_file_cache中指令参数不活动时间期间里最小的文件数
open_file_cache_errors
#指定了当搜索一个文件时是否缓存错误信息
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
#指定缓存文件的类型
{
expires 3650d;
#指定缓存时间
}
location ~ .*\.(js|css)?$
{
expires 3d;
}
SSL certificate configuration and redirect HTTPS configuration
server {
listen 192.168.1.250:443 ssl;
server_tokens off;
server_name mingonggex.com www.mingonggex.com;
root /var/www/mingonggex.com/public_html;
ssl_certificate /etc/nginx/sites-enabled/certs/mingongge.crt;
ssl_certificate_key /etc/nginx/sites-enabled/certs/mingongge.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
}
# Permanent Redirect for HTTP to HTTPS
server
{
listen 80;
server_name mingongge.com;
return 301 https://$server_name$request_uri;
}
Traffic mirroring function
location / {
mirror /mirror;
proxy_pass http://backend;
}
location = /mirror {
internal;
proxy_pass http://test_backend$request_uri;
}
Current limiting function
There are two main commands for flow restriction configuration, limit_req_zone
and limit_req
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
location /login/ {
limit_req zone=mylimit;
proxy_pass http://my_upstream;
}
}
For more and more detailed current limiting configurations, please refer to: Sunflower Collection! One article to get the Nginx current limit configuration
Nginx commonly used built-in variables
Security configuration
Disable the server_tokens item
When server_tokens is turned on, the 404 page will display the current version number of Nginx. This is obviously not safe, because hackers will use this information to try the vulnerabilities of the corresponding Nginx version. Just set server_tokens off in the http module in nginx.conf, for example:
server {
listen 192.168.1.250:80;
Server_tokens off;
server_name mingongge.com www.mingongge.com;
access_log /var/www/logs/mingongge.access.log;
error_log /var/www/logs/mingonggex.error.log error;
root /var/www/mingongge.com/public_html;
index index.html index.htm;
}
#重启Nginx后生效:
Prohibit illegal HTTP User Agents
User Agent is an identification of the browser in the HTTP protocol. Prohibiting illegal User Agents can block some requests from crawlers and scanners and prevent these requests from consuming a large amount of Nginx server resources.
For better maintenance, it is best to create a file that contains a list of undesired user agents. For example, /etc/nginx/blockuseragents.rules contains the following content:
map $http_user_agent $blockedagent {
default 0;
~*malicious 1;
~*bot 1;
~*backdoor 1;
~*crawler 1;
~*bandit 1;
}
Then put the following statement into the server module of the configuration file
include /etc/nginx/blockuseragents.rules;
并加入if语句设置阻止后进入的页面:
Prevent pictures from linking
location /img/ {
valid_referers none blocked 192.168.1.250;
if ($invalid_referer) {
return 403;
}
}
Block malicious access
very exciting! Use Nginx to block malicious access
Ban unneeded HTTP methods
Some web sites and applications may only support GET, POST and HEAD methods. Adding the following methods to the serve r module in the configuration file can prevent some spoofing attacks
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 444;
}
Disable SSL and only open TLS
Try to avoid using SSL, use TLS instead, the following configuration can be placed in the Server module
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
After this series of configurations, I believe that your Nginx server is enough to meet actual production needs.
You are also welcome to leave a message to supplement this common configuration list so that it is more complete and perfect.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。