Nginx教程 3.Nginx部署Web网站常用配置

Nginx教程 3.Nginx部署Web网站常用配置,第1张

反向代理
server {
    listen       80;
    server_name  127.0.0.1 terrybg.com www.terrybg.com;
	
    location /api {
        proxy_pass   http://172.17.0.2:8080;
    }
}

listen:监听端口

server_name:配置的访问地址(可以配置ip、域名并且可以配置多个)。

location:配置访问的资源“/api”

proxy_pass:反向代理的目标地址.表示访问“/api”时自动代理到http://172.17.0.2:8080

前端的打包文件

一般前端打包会生成dist目录,通常在我们使用nginx部署情况下将dist目录放到html目录下,配置如下:

server {
    listen       80;
    server_name  127.0.0.1 terrybg.com www.terrybg.com;
    
    # 配置前端打包
    location / {			
    	root   html/dist;
    	index  index.html index.htm;
    	try_files $uri $uri/ @router;
    }

    # 防止前端路由刷新404问题
	location @router {
		rewrite ^.*$ /index.html last;
	}
}
解决跨域问题

通常情况下我们可以使用nginx充当网关的作用,通过搭配反向代理解决跨域,配置如下:

server {
    listen       80;
    server_name  127.0.0.1 terrybg.com www.terrybg.com;
    
    # 配置前端打包
    location / {			
    	root   html/dist;
    	index  index.html index.htm;
    	try_files $uri $uri/ @router;
    }

    # 防止前端路由刷新404问题
	location @router {
		rewrite ^.*$ /index.html last;
	}
    
    location /api01 {
        proxy_pass   http://172.17.0.2:8080;
    }

    location /api02 {
        proxy_pass   http://172.17.0.2:8081;
    }
}

前后端分离开发,一般情况下前端本地如果跨域会在node服务配置,而打包部署后。需要通过配置不同的location资源访问来反向代理。

静态文件资源服务

服务器上可以将图片、js、css、pdf等静态文件开放供外部访问。搭建一个小型的知识库和文件库。

server {
    listen       80;
    server_name  static.terrybg.com;
	
    location /static/ {
        root   /home/app/static/;
        autoindex on;
    }
}
开启gzip压缩

在http模块中开启gzip 压缩,配置如下:

http {

	# 配置...
	
	# 开启gzip压缩
	gzip on;
	gzip_min_length  1k;
	gzip_buffers     4 16k;
	#gzip_http_version 1.0;
	gzip_comp_level 3;
	gzip_types       text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
	gzip_vary on;
	
}
配置Https

通过第三方云服务器,申请得到https证书,并且下载nginx版本。

http{
    # ssl证书
	server {
        listen 443 ssl; 
        server_name terrybg.com www.terrybg.com; 
        ssl_certificate html/ssl/www.terrybg.com_bundle.crt; 
        ssl_certificate_key html/ssl/www.terrybg.com.key;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1.2 TLSv1.3; 
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; 
        ssl_prefer_server_ciphers on;
        
        location / {
            root   html;
            index  index.html index.htm;
        }
    }
    # 配置访问80端口跳转到https
	server {
		listen 80;
		server_name terrybg.com www.terrybg.com;
		return 301 https://$host$request_uri; 
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/893780.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存