最简单的test.com → http://127.0.0.1:8888
server {
listen 80;
server_name test.com;
location / {
proxy_pass http://127.0.0.1:8888;
}
}
但是这样的话 请求头里面 host 能看到是 127.0.0.1:8888
要改的话 这么写
server {
listen 80;
server_name test.com;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;//改请求头 $host 浏览器原本的host
}
}
这样请求头里面 host 就是 test.com 了 原来浏览器请求的
可以看到 nginx可以改所有请求头 响应头
缓存
proxy_cache_path cache levels=1:2 keys_zone=my_cache:10m;
server {
listen 80;
server_name test.com;
location / {
proxy_cache my_cache;//上面自己取的名字
proxy_pass http://127.0.0.1:8888;
}
}
cache
是相对路径 就是ngnix安装目录下 新建cache文件来保存缓存(是的缓存数据保存在磁盘)
levels=1:2
分二级目录,方便快速查找
keys_zone=my_cache:10m
在内存里面 用10m来保存 url和缓存的对应关系
my_cache
是自定义的一个名字 下面用这个名字来使用缓存
注意 如果响应头里面有 Cache-Control:private
就可以禁止nginx缓存 这个是表示只有浏览器本身能缓存
'Cache-Control:s-maxage' 缓存寿命 是专门为nginx这种代理缓存设的寿命
配https
server {
listen 443 ; #https默认端口
server_name test.com;
ssl on;# 开启 配公钥私钥文件
ssl_certificate_key ../certs/localhost-privkey.pem;
ssl_certificate ../certs/localhost-cert.pem;
location / {
proxy_pass http://127.0.0.1:8888;
}
}
转到对应https
要达到这种效果浏览器访问http://test.com/ 给返回302跳转https://test.com/
image.png
server {
listen 80;
listen [::]:80 default_server;
server_name test.com;
return 302 https://$server_name$request_uri;
}