安裝
正式開始前,編譯環境gcc g++ 開發庫之類的需要提前裝好
安裝make:
yum -y install gcc automake autoconf libtool make
安裝g++:
yum install gcc gcc-c++
安裝pcre
yum -y install pcre*
openssl依賴
yum -y install openssl*
-
下載 - 路徑失效可在官網下載 傳送鏈
wget http://nginx.org/download/nginx-1.20.1.tar.gz
-
解壓、安裝
tar -zxvf nginx-1.20.1.tar.gz
cd nginx-1.20.1
// 配置
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make -j4 // 編譯
make install // 安裝
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin //軟鏈接
- 檢查是否正確
nginx -t
輸出成功
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
-
啟動
nginx
-
常用命令
Nginx 是支持熱啟動的, Nginx 從新讀取配置的命令是
nginx -s reload
-
停止
pkill -9 nginx
-
重啟Nginx服務
nginx -s reload
-
版本信息
nginx -V
-
配置
- 進入配置文件
cd /usr/local/nginx/conf
vim nginx.conf
- 配置反向代理/靜態資源服務器/正向代理
反向代理
反向代理應該是Nginx做的最多的一件事了。反向代理(Reverse Proxy)方式是指以代理服務器來接受internet上的連接請求,然后將請求轉發給內部網絡上的服務器,並將從服務器上得到的結果返回給internet上請求連接的客戶端,此時代理服務器對外就表現為一個反向代理服務器。簡單來說就是真實的服務器不能直接被外部網絡訪問,所以需要一台代理服務器,而代理服務器能被外部網絡訪問的同時又跟真實服務器在同一個網絡環境,當然也可能是同一台服務器,端口不同而已。
下面貼上一段簡單的實現反向代理的代碼
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:300;
proxy_set_header Host $host:$server_port;
}
}
支持https
將申請好的證書下載后,放在Nginx的安裝目錄/usr/local/nginx/conf/cert下(創建cert目錄),並且將“server.key”和“server.crt”拷貝到nginx的“cert”目錄下。
# HTTPS server
#
server {
listen 443 ssl;
server_name localhost;
ssl_certificate cert/server.crt;
ssl_certificate_key cert/server.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host:$server_port;
}
}
配置完成重啟nginx nginx -s reload
http實現自動跳轉https的設置方法
在配置80端口的文件里面,寫入以下內容即可。
server {
listen 80;
server_name localhost;
rewrite ^(.*)$ https://$host$1 permanent;
}
配置完成重啟nginx nginx -s reload