Nginx是一個十分輕量級而且高性能HTTP和反向代理服務器,一樣也是一個IMAP/POP3/SMTP代理服務器。html
nginx模塊通常分爲三類:nginx
sudo apt-get install nginx
這種方式安裝的文件位置:web
/usr/sbin/nginx:主程序shell
/etc/nginx:存放配置文件ubuntu
/usr/share/nginx:存放靜態文件segmentfault
/var/log/nginx:存放日誌後端
經過這種方式安裝的,會自動建立服務,會自動在/etc/init.d/nginx
新建服務腳本,而後就可使用sudo service nginx {start|stop|restart|reload|force-reload|status|configtest|rotate|upgrade}
的命令啓動。瀏覽器
能夠再/var/log/nginx/
下查看日誌,若是端口80被佔用,就更改/etc/nginx/sites-enabled/default
文件,將下面的兩個80改爲你想要的的端口,而後從新啓動。tomcat
19 20 server { 21 listen 80 default_server; 22 listen [::]:80 default_server ipv6only=on;
在/etc/nginx/nginx.conf
中能夠看到自定義配置文件的路徑:服務器
71 include /etc/nginx/conf.d/*.conf; 72 include /etc/nginx/sites-enabled/*; 73 }
在conf.d目錄下新建文件timeline.conf
,寫入配置內容
# HTTP Server server { listen 8080; server_name bonnenuit.vip www.bonnenuit.vip; location / { alias /home/wangjun/tomcat8/webapps/timeline/pages/; index index.html; } }
重啓nginxsudo service nginx restart
http://bonnenuit.vip:8080/ 若是顯示正常,則說明配置成功。
1. 報錯"server" directive is not allowed here in /etc/nginx/myconf/timeline.conf:3
出現這個錯誤的緣由是include /etc/nginx/xxx/*.conf;
沒有寫在http標籤下,由於server只能出如今http下面。
2. 訪問url的時候報錯403 forbidden
查詢/var/log/nginx/error.log
,具體的報錯日誌爲:
2019/07/03 10:21:25 [error] 1523#0: *1 open() "/home/wangjun/tomcat8/webapps/timeline/pages/timeline/pages/index.html" failed (13: Permission denied), client: 106.39.75.134, server: bonnenuit.vip, request: "GET /timeline/pages/index.html HTTP/1.1", host: "bonnenuit.vip:8080"
出現這個緣由是由於nginx的worker進程沒法訪問靜態資源文件,由於worker進程的用戶和資源的全部者是不同的,咱們須要更改配置文件nginx.conf
:
# user 用戶 用戶組 user wangjun wangjun;
而後重啓nginx就能夠解決。
在conf.d目錄下timeline.conf
中,新增配置內容:
# HTTP Server # 反向代理服務器+負載均衡 upstream test_reverse_proxy { server 120.25.245.241:8080 weight=1 max_fails=2 fail_timeout=10s; server 120.25.245.241:8080 weight=1 max_fails=2 fail_timeout=10s; #兩臺機器能夠作負載均衡,目前只有一臺機器,所以ip:port同樣,一臺模擬兩臺 keepalive 16; } server { listen 8080; server_name bonnenuit.vip www.bonnenuit.vip; #server_name是爲了區別多個server時,匹配域名來決定進入哪一個server,當都不匹配時,進入配置的第一個server location / { alias /home/wangjun/tomcat8/webapps/timeline/pages/; index index.html; } location ^~ /proxy/ { proxy_set_header Host $host; proxy_pass http://test_reverse_proxy/; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_redirect off; proxy_intercept_errors on; client_max_body_size 10m; } }
http://bonnenuit.vip:8080/proxy/ 若是顯示正常,則說明配置成功。
看下location的語法:
location [ = | ~ | ~* | ^~ ] uri { ... } location @name { ... }
location 後面跟可選的修飾符,後面就是要匹配的字符,花括號是對應的配置。
修飾符含義:
= | 表示精確匹配,只有請求的url路徑與後面的字符串徹底相等時,纔會命中。 |
---|---|
~ | 表示該規則是使用正則定義的,區分大小寫 |
~* | 表示該規則是使用正則定義的,不區分大小寫 |
^~ | 表示若是該符號後面的字符是最佳匹配,採用該規則,再也不進行後續的查找 |
具體的匹配過程以下:
=
修飾符的location,結束查找,使用它的配置。基於以上的匹配過程,咱們能夠獲得如下兩點啓示:
/
的話,可使用=
來定義location。參考:https://www.cnblogs.com/Eason...