Nginx配置详解
2019-12-26 本文已影响0人
Charles2018
1.部署静态文件
部署静态文件是Web服务器的最基本任务。 只需放入.txt,.html,.zip或任何其他类型的文件,服务器就会直接将其返回。
此配置示例将侦听81端口,可以在http://localhost:81 /上进行查看,会显示一个文件目录列表 如图1所示。 还包括通过关闭目录列表并仅指定特定索引文件来在子目录上设置单独控件的示例。 它还将在/static/
的网址上提供/var/www/static-content/
目录。
server {
listen 0.0.0.0:81;
root /var/websites/public/;
location / {
# 开启目录浏览 (危险!)
autoindex on;
}
location /relative-to-root/dir {
autoindex off;
# Default to index.htm or index.html
index index.html, index.htm;
}
location /static/ {
alias /var/websites/public/static-content/;
}
}

2.创建一个反向代理
此示例配置将端口800转发到81,包括原始IP作为额外的HTTP标头X-Real-IP。 有些代理使用X-Forwarded-For代替。
server {
listen 800;
server_name 520mj.net;
location / {
proxy_pass http://localhost:81;
proxy_set_header X-Real-IP $remote_addr;
}
}


3.添加Https证书

同时监听80和443端口,当使用http访问自动跳转到https,根据if($schema ==hhtp)完成
ssl_certificate配置证书路径
ssl_certificate_key 配置key路径
保存,重启nginx。
启动发现访问 ailijie.top成功跳转为 https://ailijie.top
使用hhtps后站点内所有的请求都要使用https不然会被浏览器进行拦截。
第二种:
server {
listen 80;
listen 443 ssl;
server_name www.onlly.online onlly.online;
root /var/websites/public/;
ssl_certificate /etc/nginx/ssl/onlly.online/Nginx/onlly.online_bundle.crt;
ssl_certificate_key /etc/nginx/ssl/onlly.online/Nginx/onlly.online.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
if ($scheme = http) {
return 301 https://$host$request_uri;
}
location / {
# 开启目录浏览 (危险!)
autoindex on;
}
结果:

4.添加HTTP基本身份验证
要添加HTTP基本身份验证,您只需要配置 auth_basic和auth_basic_user_file配置变量。要生成用户文件,您将需要htpasswd 可执行文件。您可以通过两种方式安装它:
如果提示没有安装apache2-utils
则按照提示先安装即可
4.1生成密码
printf "your_username:$(openssl passwd -crypt your_password)\n" >> passwd
请自行替换your_username和your_password字段
4.2在服务器的nginx配置文件中,添加以下行:
server {
# ...
auth_basic "your_sites_name";
auth_basic_user_file /etc/nginx/auth/onlly.online/passwd;
# ...
}
4.2重新加载nginx配置
nginx -s reload
结果:

