Nginx配置

243 阅读2分钟

以下是使用Nginx必会的配置

location

location的作用是匹配path进行分发

location /xxx 匹配以/xxx开头的path
location = /xxx 精确匹配/xxx
location ~ ^/abc$ 必须与正则匹配,其中~表示这是一个正则,^和$是正则表达式中开头和结尾的意思
location !~ ^/abc$ 与上一行相反
location ~* ^/abc$ ~*表示正则不区分大小写
location ^~ /xxx 如果此条匹配成功,则不再往下匹配

示例

location / {
}

location /test {
}

location ~ ^/test/([0-9]*)/?$ {
  # 以/test/开头,后面是数字,最后的/可有可无,可以匹配/test/123
}

rewrite

将任意path重写到指定path,并且不改变URL

location / {
  rewrite /test/(.*)+/? /index.html?s=$1;
}

上面示例中如果服务器上并没有/test/xxx目录,访问/test/xxx应该要返回404,但是由于添加了rewrite规则,导致实际去访问/index.html?s=xxx,对于用户来说并不知道,还以为访问的是/test/xxx

上面的配置存在一个问题,如果服务器上有/test/xxx这个目录,也仍然会进行rewrite,不希望这样的话,需要rewrite之前判断文件或目录是否存在,如果不存在才rewrite

if ( !-d $request_filename ) {
    # 不是目录,就设置变量rf的值为1
    set $rf 1$rf;
}
if ( !-f $request_filename ) {
    # 不是文件,就设置变量rf的值为21
    set $rf 2$rf;
}
if ( $rf = 21 ) {
    # 只有变量rf=21才说明即不是文件也不是目录
    rewrite /test/(.*)+/? /index.html?id=$1;
}

try_files

尝试打开指定path的文件,如果文件不存在,则继续打开下一个文件,如果都打不开则会返回500

location / {
  try_files $uri $uri/ /index.html;
}

假设有上面这样的配置,访问/test/123时,会尝试打开/test/123这个文件,如果不存在就尝试打开/test/123/这个目录,如果还不存在就打开/index.html,而index.html文件中可以通过js获取到URL进而得到/test/123,再自己实现相应的路由

也可以使用别名

location / {
  try_files $uri $uri/ @test;
}

location @test {
  # 做相应的处理
}

负载均衡

先定义上游服务

upstream api {
  # 可以添加很多后端服务器,也可以指定健康检查
  server 192.168.0.28:8088;

  keepalive 300;
  keepalive_requests 1000;
  keepalive_timeout 60s;
}
server {
  listen 80;
  server_name ahydd.com;
  root /usr/share/nginx/html/;

  location /api {
    proxy_pass http://api;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
  }
}

http跳https

server {
  listen 80;
  server_name ahydd.com;
  return 301 https://$server_name$request_uri;
}

禁止某些请求方式

禁止GET|POST|PUT|DELETE|OPTIONS之外的请求

location / {
  if ($request_method !~ ^(GET|POST|PUT|DELETE|OPTIONS)$ ) {
    return 403;
  }
}

通用的起始设置

user root;
worker_processes  auto;

worker_rlimit_nofile 65535;

events {
	worker_connections  102400;
	use epoll;
}

http {
	server_tokens off;
	include mime.types;
	default_type application/octet-stream;

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

	keepalive_timeout  65;
	client_max_body_size 20m;
	
	gzip on;
	gzip_disable "msie6";
	gzip_min_length 1000;
	gzip_proxied expired no-cache no-store private auth;
	gzip_types text/plain application/xml application/javascript text/css application/x-javascript;

	upstream api {
		server 192.168.0.28:8088;
		
		keepalive 300;
		keepalive_requests 1000;
		keepalive_timeout 60s;
	}

	server {
		listen 80;
		server_name empty;
	}

	server {
		listen 80;
		server_name ahydd.com;
		root /usr/share/nginx/html/;

		location / {
			try_files $uri $uri/ /index.html;
		}

		location /api {
			proxy_pass http://api;
			proxy_http_version 1.1;
			proxy_set_header Connection "";
		}
	}

}

公众号:飞翔的代码