nginx应用

发布于:2024-03-15 ⋅ 阅读:(65) ⋅ 点赞:(0)

应用场景一:web服务器

server {
	listen 80;
	server_name _;
	location / {
		root /data/wwwroot;
		index index.html index.htm;
	}
}
server {
	listen 443 ssl;
	server_name _;
	ssl_certificate /path/to/certificate.crt;
	ssl_certificate _kry /path/to/certificate-kry.key;
	location / {
		root /data/wwwroot;
		index index.html index.htm;
	}
}

应用场景二:反向代理服务器

server {
	listen 80;
	server_name _;
	location / {
		proxy_pass http://192.168.1.1;
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr;
	}
}

应用场景三:负载均衡器

upstream webservers {
	ip_hash; #会话保持
	server 192.168.1.1:8080;
	server 192.168.1.2:8080;
}
server {
	listen 80;
	server_name _;
	location / {
		proxy_pass http://webservers;
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr;

应用场景四:URL重定向

#域名重定向
server {
	listen 80;
	server_name old.test.com;
	location / {
		rewrite ^/(.*)$ http://new.test.com/$1;
	}
}
#路径重定向
server {
	listen 80;
	server_name old.test.com;
	location / {
		rewrite ^/old-path/(.*)$ /new-path/$1;
	}
}

应用场景五:防盗链

server {
	listen 80;
	server_name _;
	location ~* \.(gif|jpg|png)$ {
		valid_referers none blocked *.test.com;
		if ($invalid_referer) {
			return 403;
		}
	}
}

应用场景六:手机端重定向PC端

server {
	listen 80;
	server_name _;
	location / {
		if ($http_usre_agent ~* '(android|iphone|ipad)') {
			rewrite ^/(.*)$ https://pc.test.com/$1;
		}
	}
}

应用场景七:基于请求路径转发不同服务

server {
	listen 80;
	server_name _;
	location / {
		proxy_pass http://192.168.1.1;
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr;
	location /001 {
		proxy_pass http://192.168.1.2;
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr;
	location /002 {
		proxy_pass http://192.168.1.3;
		proxy_set_header Host $host; 
		proxy_set_header X-Real-IP $remote_addr;
	}
}

补充:四层转发

nginx.conf中加入如下配置时

# 四层负载不在http模块里面,和http模块同级别
http {
}

stream {
    upstream mysql {
	server 127.0.0.1:3306;
    }
    server {
        listen 61306;
        proxy_connect_timeout  10s;
        proxy_timeout  30s;
        proxy_pass  mysql;
    }

解决方法:

1、yum -y install epel-release

2、yum -y install nginx-all-modules.noarch


3、nginx.conf最顶部加入:load_module /usr/lib64/nginx/modules/ngx_stream_module.so;

4、nginx -t 检查nginx配置文件内容语法是否正确(nginx -V查看版本号);