本篇文章主要解决以下几个问题:
- 前后端分离项目如何配置Nginx
- 配置https协议访问
- 开启http访问但强制跳转https访问
基本的安装就不多说了,直奔主题。
本文基于ubuntu系统,另外假定有几个前提条件:
- 主机地址为
192.168.10.10
- 后端项目启动端口为
192.168.10.10:8000
- 前端代码会调用后端的info和test两个url地址
- 前端静态文件目录 /var/www/html/project
1 基本配置
http下server基本配置如下
server {
listen 80;
server_name 192.168.10.10
# 配置根地址访问的静态资源
location /{
root /var/www/html/project;
}
# 配置可被nginx转发的接口地址
location /info{
proxy_pass http://127.0.0.1:8000;
}
location /test{
proxy_pass http://127.0.0.1:8000;
}
}
现在访问http://192.168.10.10 就可以进去首页了
如果访问不了首页,可以尝试修改location / 为以下内容:
location /{
root /var/www/html/project;
index index.html index.htm;
try_files $uri /index.html;
}
2 配置HTTPS
参考:https://cloud.tencent.com/developer/article/1346683
配置https,可以使用自签名证书和购买机构颁发的证书。
这里我们使用自签名证书。
执行以下语句生成签名和秘钥
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt
将会有如下所示:
OutputCountry Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc.
Organizational Unit Name (eg, section) []:Ministry of Water Slides
Common Name (e.g. server FQDN or YOUR name) []:server_IP_address
Email Address []:admin@your_domain.com
适当填写提示。
最重要的一行是Common Name (e.g. server FQDN or YOUR name)那一行,您需要输入与服务器关联的域名,或者是您服务器的公共IP地址。
现在主机里面已经有以下两个文件了
/etc/ssl/private/nginx-selfsigned.key
/etc/ssl/certs/nginx-selfsigned.crt
继续填写nginx配置,我们新增一栏server,填写以下配置
server {
listen 443;
server_name 192.168.10.10
ssl on;
ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
# 配置根地址访问的静态资源
location /{
root /var/www/html/project;
}
# 配置可被nginx转发的接口地址
location /info{
proxy_pass http://127.0.0.1:8000;
}
location /test{
proxy_pass http://127.0.0.1:8000;
}
}
现在就可以访问https://192.168.10.10 了
3 http跳转https
在http的nginx的配置中加一句重定向 rewrite ^(.*)$ https://$host permanent; 即可
整个配置如下
server {
listen 80;
server_name 192.168.10.10
# http强制跳转https地址
rewrite ^(.*)$ https://$host permanent;
# 配置根地址访问的静态资源
location /{
root /var/www/html/project;
}
# 配置可被nginx转发的接口地址
location /info{
proxy_pass http://127.0.0.1:8000;
}
location /test{
proxy_pass http://127.0.0.1:8000;
}
}
4 注意
location /{
root /var/www/html/project;
index index.html index.htm;
try_files $uri /index.html;
}
以上配置可能导致的问题,在地址后面加上任意的后缀后能访问首页,例如http://192.168.10.10/qwewqr/
这样的配置实际上是不正确的,去掉以下内容后,就能提示404 No Found 了
index index.html index.htm;
try_files $uri /index.html;
|