server{
listen 80;
server_name domain;
rewrite ^(.*)$ https://$host$1 permanent;
}
server{
listen 443;
server_name domain;
index index.html index.htm index.php default.html default.htm default.php;
ssl on;
ssl_certificate cert/domain.pem;
ssl_certificate_key cert/domain.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
root /data/path/;
include rewrite/none.conf;
#error_page 404 /404.html;
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
break;
}
}
location ~ .*\.(php|php5)?$
{
try_files $uri =404;
fastcgi_pass 127.0.0.1:9001;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_param ENVIRONMENT 'production';
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
location ~ /.well-known {
allow all;
}
location ~ /\.
{
deny all;
}
access_log /data/log/domain.log;
error_log /data/log/domain.error.log;
}
https证书可以从阿里云那里申请免费的证书,一年有效期,到期了,重复申请即可。
上面分两个,一个是将 http 转发到https哪里去,一个是https的配置。
证书的位置,我采用的是相对的位置,虚拟主机的配置目录位置
在 /usr/local/nginx/conf/vhost
证书的位置是在:
/usr/local/nginx/conf/cert
开发的时候,注意代码编写的时候,img、css、js还有超链接,文件路径,采用
<img src="//domain/1.jpg">
等形式实现。
http2
nginx启用http2,nginx的版本必须在1.9.5以上,必须使用https协议,所以想从http1.1升级到http2,需要先让http升级成https。
修改配置如下:
listen 443 ssl http2;
nginx在 nginx1.13.9 后就开始支持server push了,如果nginx版本支持,需要可以新增这个配置:
http2_push_preload on;
这样我们在后端语言上,可以动态设置需要推送的资源:
<?php
//这里会有一个问题,第一次请求会实现服务器推,浏览器已经得到资源了
//第二次访问还是服务器还是会推,这个问题,可以使用session
//每次请求来,都记录已经推送过去什么,没有就退,有就不推。
$arr = [
'</http2-push/1.jpg>; rel=preload; as=image',
'</http2-push/jquery-3.6.0.min.js>; rel=preload; as=script',
];
$str = implode(',', $arr);
header("Link: $str");
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>http2 server push</title>
</head>
<body>
<img src="./1.jpg" alt="">
<div id="http2">测试加载图片和js</div>
<script src="./jquery-3.6.0.min.js"></script>
<script>
console.log($('#http2').html());
</script>
</body>
</html>
相关参考资源: