Nginx配置笔记

Nginx配置笔记

hash070 626 2022-07-11

本篇文章用于记录如何使用、配置和管理Nginx。

Ngixn配置文件的位置

使用nginx -t命令可以方便地查看配置文件的位置

[root@server ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

如上面的代码所示,在这个系统中,Nginx的配置文件位置应为:/etc/nginx/nginx.conf

配置文件结构

Nginx的config配置文件结构如下图和代码所示

1670043211226.webp

...              #全局块
events {         #events块
   ...
}
http      #http块
{
    ...   #http全局块
    server        #server块
    {
        ...       #server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN]
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块
}

**1、全局块:**配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

**2、events块:**配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

**3、http块:**可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

**4、server块:**配置虚拟主机的相关参数,一个http中可以有多个server。

**5、location块:**配置请求的路由,以及各种页面的处理情况。

Nginx基础示例配置

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
worker_rlimit_nofile 51200;


events {
	worker_connections 51200;
	multi_accept on;
}

http {
	##
	# Basic Settings
	##

	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 65;
	types_hash_max_size 4096;
	# server_tokens off;

	# server_names_hash_bucket_size 64;
	# server_name_in_redirect off;
	server_names_hash_bucket_size 512;
	client_header_buffer_size 32k;
	large_client_header_buffers 4 32k;
	client_max_body_size 4096m;


	include /etc/nginx/mime.types;
	default_type application/octet-stream;

	##
	# SSL Settings
	##

	ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
	ssl_prefer_server_ciphers on;

	##
	# Logging Settings
	##

	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;

	##
	# Gzip Settings
	##

	#       gzip on;
	#
	#       gzip_vary on;
	#       gzip_proxied any;
	#       gzip_comp_level 6;
	#       gzip_buffers 16 8k;
	#       gzip_http_version 1.1;
	#       gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
	gzip on;
	gzip_min_length 1k;
	gzip_buffers 4 16k;
	gzip_http_version 1.1;
	gzip_comp_level 2;
	gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
	gzip_vary on;
	gzip_proxied expired no-cache no-store private auth;
	gzip_disable "MSIE [1-6]\.";


	##
	# Virtual Host Configs
	##
	include /etc/nginx/conf.d/*.conf;
	include /etc/nginx/sites-enabled/*;
	# Server Conf
	include /root/nginx/server/*.conf;
	# Cache
	#       proxy_cache_path /root/nginx/cache levels=1:2 keys_zone=mycache:20m max_size=2048m inactive=60m;
	#       proxy_temp_path /root/nginx/cache/temp;

	# 访问限制示例
#	limit_conn_zone $binary_remote_addr zone=op_ip_addr:10m;
#	limit_req_zone $binary_remote_addr zone=op_peripreq:10m rate=2r/s;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#}
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#}
#}

子配置文件示例

如上面的示例配置所示,如果需要新建一个网站,你可以直接修改Nginx的主配置文件然后重载生效。

但是不推荐直接修改主配置文件,如果所有网站都放到一个配置文件里会让这个文件看上去非常混乱,不利于管理

可以将网站的配置文件放到/root/ngixn/server/文件夹下,把反代文件统一放到/nginx/proxy/www.hash070.top/文件夹下面,它们都应该以.conf结尾,编写好配置后用nginx -s reload命令重载一下就OK了

独立网站Server配置文件示例

server {
	listen 80;
	server_name test.com;
	return 302 https://$server_name$request_uri;
    #	个人喜欢使用302临时重定向,因为301一旦启用难以反悔。
    #	如果想要301永久重定向的话可以将302改为301
}

server {
	listen 443 ssl http2;
	server_name test.com;
	#    index index.php index.html index.htm default.php default.htm default.html;
	#    root /root/nginx/server/test.com;

	#	ECC证书 可选
	#	ssl_certificate /root/nginx/ecc/test.com.cer;
	#	ssl_certificate_key /root/nginx/ecc/test.com.key;
	#	RSA SSL证书
	ssl_certificate /root/nginx/ssl/test.com.cer;
	ssl_certificate_key /root/nginx/ssl/test.com.key;
	ssl_protocols TLSv1.2 TLSv1.3;
	ssl_prefer_server_ciphers on;
	ssl_session_cache shared:SSL:10m;
	ssl_session_timeout 10m;
    #	HSTS严格传输安全性策略,告诉客户本站在max-age的时间内不可能使用http协议进行通信
    #	可阻止HTTP降级攻击,该配置也是一旦启用难以反悔,请根据自身需要决定是否删除下面这一行
	add_header Strict-Transport-Security "max-age=31536000";
    
	error_page 497 https://$host$request_uri;
	ssl_stapling on; #开启OCSP
	ssl_stapling_verify on; #开启OCSP验证
	resolver 8.8.8.8 1.1.1.1 valid=60s;#添加resolver解析OSCP响应服务器的主机名,valid表示缓存

	#反向代理

	location / {
		proxy_pass http://127.0.0.1:8080;
		proxy_set_header Host $http_host;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "upgrade";
		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 https;
		proxy_set_header X-Nginx-Proxy true;
		proxy_redirect off;
	}
}

相应的反向代理配置文件示例

location / {
	proxy_pass http://127.0.0.1:8080;
	proxy_set_header Host $http_host;
	proxy_http_version 1.1;
	proxy_set_header Upgrade $http_upgrade;
	proxy_set_header Connection "upgrade";
	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 https;
	proxy_set_header X-Nginx-Proxy true;
	proxy_redirect off;
}

编写好配置后建议先用nginx -t命令让Nginx检查一下配置文件是否报错

确认无误后再用nginx -s reload命令重载配置

高级反向代理配置

上面的这个反向代理是最基础的反代配置,我们可以借助upstream模块实现负载均衡,热备源站等高级设置,具体看这篇文章:https://www.hash070.top/archives/nginx-proxy-pass-and-upstream.html