Nginx的HTTPS配置、跨域配置,前端配置、安装

nginx安装

进入nginx解压目录,

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module

注意此处添加了http2和ssl模块。

make

如果你未安装过,则

make install

如果你安装过,则

mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak

cp objs/nginx /usr/local/nginx/sbin/nginx

将新生成的nginx命令复制到我们使用的nginx下,将原nginx命令备份

配置https

安装certbot客户端:

yum install certbot/ apt install certbot

certbot certonly --standalone -d 域名1 -d 域名2

此处域名为你需要配置https的域名,多个域名则多个-d 域名

然后查看日志中提示/etc/letsencrypt/live/你的域名/xxx,这个就是你的密钥文件,将其配置到nginx中。

	server {
		listen       443 ssl http2 ;
        listen       [::]:443 ssl http2 ;
        server_name  你的域名;   

             ssl_certificate "/etc/letsencrypt/live/你的域名/cert.pem";   #
        ssl_certificate_key "/etc/letsencrypt/live/你的域名/privkey.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
		
        ... 其他配置
    }	

配置Nginx跨域

location / {
				add_header 'Access-Control-Allow-Origin' $http_origin;
				add_header 'Access-Control-Allow-Credentials' 'true';
				add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
				add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
				add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
				if ($request_method = 'OPTIONS') {
					add_header 'Access-Control-Max-Age' 1728000;
					add_header 'Content-Type' 'text/plain; charset=utf-8';
					add_header 'Content-Length' 0;
					return 204;
				}
			proxy_pass http://xxxxx/;
		}

其中,重要的是:

add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
}

注意,这里这里return204如果还是跨域的话,就将204更改为200
将其加入到server下的你需要匹配的location中。

注意Nginx中加入了跨域后代码中不要再加跨域,除非你不经过Nginx

配置前端项目

location / {
            root   /usr/local/nginx/html/agency;
            index  index.html index.htm;
			try_files $uri $uri/ /index.html;
        }

注意这里的root xxxx这个是正常的,如果你是vue项目,那么当你地址栏路由更改时会404,那么则需要加入try_files $uri $uri/ /index.html;

配置静态资源映射

location /img/ {
           alias /home/software/nginx/html/img/;
           autoindex on;
}
原文地址:https://www.cnblogs.com/daihang2366/p/14808662.html