Nginx添加https访问(ubuntu16.04)——已解决
首先吐一下槽,linux不同发行版的nginx配置竟然不一样,浪费好久时间啊。ubuntu16.04的同学可以看过来了,nginx配置https和http共存,并且重定向
免费证书
按照步骤申请到阿里云免费证书
免费证书申请的时候不需要人工审核,只要绑定到相应的域名即可。阿里云上有教程,一步步跟着走即可。
申请完成后,如果审核通过即可下载证书。
使用FileZilla添加证书文件
下载证书文件后按照步骤把文件添加到服务器上,这里推荐使用FileZilla感觉比较方便,使用方法见另一篇博客这里
进入路径/var/www,然后mkdir ssl
进入目录cd ssl
将刚才解压的两个文件上传到ssl目录下,改不改名字随意。此时filezilla中可以看到如下状况:
最后一步
是的!你没有听错!就是最后一步~
sudo vim /etc/nginx/sites-available/default
按i
进入编辑模式,把下面几乎复制粘贴即可:该修改的自己修改一下
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
# SSL configuration
#
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
# ssl on;
ssl_certificate /var/www/ssl/*****.pem;
ssl_certificate_key /var/www/ssl/*****.key;
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/TA-Project/public;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
server_name yourip;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.php?$query_string;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
解释在这里:
- SSL configuration下面的配置即证书配置,其余copy,只要更改
ssl_certificate /var/www/ssl/*****.pem;
ssl_certificate_key /var/www/ssl/*****.key;
- 网站根目录设定:root 后面跟上网站根目录,可以看到我这里用的是laravel,所以根目录是项目名/public
root /var/www/TA-Project/public;
- 服务器ip设置:填你的域名
sever_name yourdomain;
配置完毕:重启nginx服务即可
service nginx restart
补充
标题说可以配置重定向,那就再加上一段
server {
listen 80;
server_name www.ustcta.com;
add_header Strict-Transport-Security max-age=15768000;
return 301 https://$server_name$request_uri;
}
这一段配置补充在刚刚的sever那段前面即可,已经有了重定向功能.现在直接输入你的域名,浏览器会自动以https访问啦.
希望对ubuntu用户有帮助~如果你有好的建议也可以私信我✌