Nginx基本配置備忘
Nginx 配置
在了解具體的Nginx配置項之前我們需要對于Nginx配置文件的構成有所概念,一般來說,Nginx配置文件會由如下幾個部分構成:
# 全局塊
...
# events塊
events {
...
}
# http塊
http
{
# http全局塊
...
# 虛擬主機server塊
server
{
# server全局塊
...
# location塊
location [PATTERN]
{
...
}
location [PATTERN]
{
...
}
}
server
{
...
}
# http全局塊
...
}
在上述配置中我們可以看出,Nginx配置文件由以下幾個部分構成:
-
全局塊:配置影響nginx全局的指令。一般有運行nginx服務器的用戶組,nginx進程pid存放路徑,日志存放路徑,配置文件引入,允許生成worker process數等。
-
events塊:配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。
-
http塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方模塊的配置。如文件引入,mime-type定義,日志自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。
-
server塊:配置虛擬主機的相關參數,一個http中可以有多個server。
-
location塊:配置請求的路由,以及各種頁面的處理情況。
########### 每個指令必須有分號結束。#################
#user administrator administrators; #配置用戶或者組,默認為nobody nobody。
#worker_processes 2; #允許生成的進程數,默認為1
#pid /nginx/pid/nginx.pid; #指定nginx進程運行文件存放地址
error_log log/error.log debug; #制定日志路徑,級別。這個設置可以放入全局塊,http塊,server塊,級別以此為:debug|info|notice|warn|error|crit|alert|emerg
events {
accept_mutex on; #設置網路連接序列化,防止驚群現象發生,默認為on
multi_accept on; #設置一個進程是否同時接受多個網絡連接,默認為off
#use epoll; #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
worker_connections 1024; #最大連接數,默認為512
}
http {
include mime.types; #文件擴展名與文件類型映射表
default_type application/octet-stream; #默認文件類型,默認為text/plain
#access_log off; #取消服務日志
log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定義格式
access_log log/access.log myFormat; #combined為日志格式的默認值
sendfile on; #允許sendfile方式傳輸文件,默認為off,可以在http塊,server塊,location塊。
sendfile_max_chunk 100k; #每個進程每次調用傳輸數量不能大于設定的值,默認為0,即不設上限。
keepalive_timeout 65; #連接超時時間,默認為75s,可以在http,server,location塊。
# 定義常量
upstream mysvr {
server 127.0.0.1:7878;
server 192.168.10.121:3333 backup; #熱備
}
error_page 404 https://www.baidu.com; #錯誤頁
#定義某個負載均衡服務器
server {
keepalive_requests 120; #單連接請求上限次數。
listen 4545; #監聽端口
server_name 127.0.0.1; #監聽地址
location ~*^.+$ { #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。
#root path; #根目錄
#index vv.txt; #設置默認頁
proxy_pass http://mysvr; #請求轉向mysvr 定義的服務器列表
deny 127.0.0.1; #拒絕的ip
allow 172.18.5.54; #允許的ip
}
}
}
虛擬主機與靜態站點
本部分概述如何配置Nginx進行靜態內容服務,Nginx的靜態內容分發能力還是非常強大的。
http {
server {
listen 80;
server_name www.domain1.com;
access_log logs/domain1.access.log main;
location / {
index index.html;
root /var/www/domain1.com/htdocs;
}
}
server {
listen 80;
server_name www.domain2.com;
access_log logs/domain2.access.log main;
location / {
index index.html;
root /var/www/domain2.com/htdocs;
}
}
}
虛擬主機配置詳解
主機與端口
listen 127.0.0.1:8000;
listen *:8000;
listen localhost:8000;
# IPV6
listen [::]:8000;
# other params
listen 443 default_serer ssl;
listen 127.0.0.1 default_server accept_filter=dataready backlog=1024
服務域名
# 支持多域名配置
server_name www.barretlee.com barretlee.com;
# 支持泛域名解析
server_name *.barretlee.com;
# 支持對于域名的正則匹配
server_name ~^\.barret\.com$;
URI匹配
location = / {
# 完全匹配 =
# 大小寫敏感 ~
# 忽略大小寫 ~*
}
location ^~ /images/ {
# 前半部分匹配 ^~
# 可以使用正則,如:
# location ~* \.(gif|jpg|png)$ { }
}
location / {
# 如果以上都未匹配,會進入這里
}
文件路徑配置
根目錄
location / {
root /home/barret/test/;
}
別名
location /blog {
alias /home/barret/www/blog/;
}
location ~ ^/blog/(\d+)/([\w-]+)$ {
# /blog/20141202/article-name
# -> /blog/20141202-article-name.md
alias /home/barret/www/blog/$1-$2.md;
}
首頁
index /html/index.html /php/index.php;
重定向頁面
error_page 404 /404.html;
error_page 502 503 /50x.html;
error_page 404 =200 /1x1.gif;
location / {
error_page 404 @fallback;
}
location @fallback {
# 將請求反向代理到上游服務器處理
proxy_pass http://localhost:9000;
}
try_files
try_files $uri $uri.html $uri/index.html @other;
location @other {
# 嘗試尋找匹配 uri 的文件,失敗了就會轉到上游處理
proxy_pass http://localhost:9000;
}
location / {
# 嘗試尋找匹配 uri 的文件,沒找到直接返回 502
try_files $uri $uri.html =502;
}
緩存配置
Expire:過期時間
在Nginx中可以配置緩存的過期時間:
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
expires 30d;
add_header Vary Accept-Encoding;
access_log off;
}
我們也可以添加更復雜的配置項:
location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html|xml|otf|ttf|eot|woff|svg)$ {
access_log off;
expires 30d;
## No need to bleed constant updates. Send the all shebang in one
## fell swoop.
tcp_nodelay off;
## Set the OS file cache.
open_file_cache max=3000 inactive=120s;
open_file_cache_valid 45s;
open_file_cache_min_uses 2;
open_file_cache_errors off;
}
反向代理
events{
}
http{
upstream ggzy {
server 127.0.0.1:1398 weight=3;
server 127.0.0.1:1399;
}
# 80端口配置,可配置多個Virtual Host
server {
listen 80;
index index index.htm index.py index.html;
server_name app.truelore.cn;
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http//ggzy;
}
}
}
NodeJS Application
const http = require('http');
http.createServer((req, res) => {
res.end('hello world');
}).listen(9000);
任何請求過來都返回 hello world,簡版的 Nginx 配置如下,
events {
# 這里可不寫東西
use epoll;
}
http {
server {
listen 127.0.0.1:8888;
# 如果請求路徑跟文件路徑按照如下方式匹配找到了,直接返回
try_files $uri $uri/index.html;
location ~* ^/(js|css|image|font)/$ {
# 靜態資源都在 static 文件夾下
root /home/barret/www/static/;
}
location /app {
# Node.js 在 9000 開了一個監聽端口
proxy_pass http://127.0.0.1:9000;
}
# 上面處理出錯或者未找到的,返回對應狀態碼文件
error_page 404 /404.html;
error_page 502 503 504 /50x.html;
}
}
首先 try_files,嘗試直接匹配文件;沒找到就匹配靜態資源;還沒找到就交給 Node 處理;否則就返回 4xx/5xx 的狀態碼。
Upstream Cache
http {
,,,,,
proxy_cache_path /var/cache/nginx/cache levels=1:2 keys_zone=imgcache:100m inactive=1d max_size=10g;
server {
........
location ~* ^.+\.(js|ico|gif|jpg|jpeg|png|html|htm)$ {
log_not_found off;
access_log off;
expires 7d;
proxy_pass http://img.example.com ;
proxy_cache imgcache;
proxy_cache_valid 200 302 1d;
proxy_cache_valid 404 10m;
proxy_cache_valid any 1h;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
}
}
}
HTTPS
Let's Encrypt 證書申請
Let's Encrypt 為我們提供了非常方便的命令行工具 certbot ,筆者是在Ubuntu 16.04的機器上進行配置,因此只要執行如下命令即可:
# 安裝letsencrypt命令行
$ sudo apt-get install letsencrypt
# 獨立的為example.com與www.example.com申請證書
$ letsencrypt certonly --standalone -d example.com -d www.example.com
# 自動執行證書刷新操作
$ letsencrypt renew --dry-run --agree-tos
基本HTTPS配置
基本的HTTPS支持配置如下:
server {
listen 192.168.1.11:443; #ssl端口
server_name test.com;
#為一個server{......}開啟ssl支持
ssl on;
#指定PEM格式的證書文件
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私鑰文件
ssl_certificate_key /etc/nginx/test.key;
}
在真實的生產環境中,我們的配置如下:
server {
# 如果需要spdy也可以加上,lnmp1.2及其后版本都默認支持spdy,lnmp1.3 nginx 1.9.5以上版本默認支持http2
listen 443 ssl;
# 這里是你的域名
server_name www.vpser.net;
index index.html index.htm index.php default.html default.htm default.php;
# 網站目錄
root /home/wwwroot/www.vpser.net;
# 前面生成的證書,改一下里面的域名就行
ssl_certificate /etc/letsencrypt/live/www.vpser.net/fullchain.pem;
# 前面生成的密鑰,改一下里面的域名就行
ssl_certificate_key /etc/letsencrypt/live/www.vpser.net/privkey.pem;
ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
#這個是偽靜態根據自己的需求改成其他或刪除
include wordpress.conf;
#error_page 404 /404.html;
location ~ [^/]\.php(/|$)
{
# comment try_files $uri =404; to enable pathinfo
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
# lnmp 1.0及之前版本替換為include fcgi.conf;
include fastcgi.conf;
#include pathinfo.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
access_log off;
}
強制HTTP轉到HTTPS
Nginx Rewrite
server {
listen 192.168.1.111:80;
server_name test.com;
rewrite ^(.*)$ https://$host$1 permanent;
}
Nginx 497錯誤碼
利用error_page命令將497狀態碼的鏈接重定向到 https:// test.com 這個域名上
server {
listen 192.168.1.11:443; #ssl端口
listen 192.168.1.11:80; #用戶習慣用http訪問,加上80,后面通過497狀態碼讓它自動跳到443端口
server_name test.com;
#為一個server{......}開啟ssl支持
ssl on;
#指定PEM格式的證書文件
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私鑰文件
ssl_certificate_key /etc/nginx/test.key;
#讓http請求重定向到https請求
error_page 497 https://$host$uri?$args;
}
Meta刷新,前端跳轉
在HTTP正常返回的頁面中添加meta屬性:
<html>
<meta http-equiv="refresh" content="0;url=https://test.com/">
</html>
server {
listen 192.168.1.11:80;
server_name test.com;
location / {
#index.html放在虛擬主機監聽的根目錄下
root /srv/www/http.test.com/;
}
#將404的頁面重定向到https的首頁
error_page 404 https://test.com/;
}
反向HTTPS轉發到內部HTTP
來自:https://zhuanlan.zhihu.com/p/24524057