linux下安裝Nginx
(nginx關鍵字:反向代理,負載均衡)
1、安裝gcc
安裝 nginx 需要先將官網下載的源碼進行編譯,編譯依賴 gcc 環境,如果沒有 gcc 環境,則需要安裝:
yum install gcc-c++
2、PCRE pcre-devel 安裝
PCRE(Perl Compatible Regular Expressions) 是一個Perl庫,包括 perl 兼容的正則表達式庫。nginx 的 http 模塊使用 pcre 來解析正則表達式,所以需要在 linux 上安裝 pcre 庫,pcre-devel 是使用 pcre 開發的一個二次開發庫。nginx也需要此庫。命令:
yum install -y pcre pcre-devel
3、zlib 安裝
zlib 庫提供了很多種壓縮和解壓縮的方式, nginx 使用 zlib 對 http 包的內容進行 gzip ,所以需要在 Centos 上安裝 zlib 庫。
yum install -y zlib zlib-devel
4、OpenSSL 安裝
OpenSSL 是一個強大的安全套接字層密碼庫,囊括主要的密碼算法、常用的密鑰和證書封裝管理功能及 SSL 協議,並提供豐富的應用程序供測試或其它目的使用。
nginx 不僅支持 http 協議,還支持 https(即在ssl協議上傳輸http),所以需要在 Centos 安裝 OpenSSL 庫。
yum install -y openssl openssl-devel
5、下載安裝包
手動下載.tar.gz安裝包,地址:https://nginx.org/en/download.html
下載完畢上傳到服務器上 /root
6、解壓
tar -zxvf nginx-1.18.0.tar.gz
cd nginx-1.18.0
7、配置
使用默認配置,在nginx根目錄下執行
1、./configure
2、make
3、make install
查找安裝路徑:
whereis nginx
Nginx常用命令
cd /usr/local/nginx/sbin/
./nginx 啟動
./nginx -s stop 停止
./nginx -s quit 安全退出
./nginx -s reload 重新加載配置文件
如果報:nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
因為/usr/local/nginx/logs/nginx.pid這個文件不存在
解決:/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf,使用nginx -c的參數指定nginx.conf文件的位置,然后進入log目錄,發現有了nginx.pid文件,再執行./nginx -s reload
ps aux|grep nginx 查看nginx進程
啟動成功訪問 服務器ip:80
注意:如何連接不上,檢查阿里雲安全組是否開放端口,或者服務器防火牆是否開放端口!
相關命令:
**開啟**
service firewalld start
**重啟**
service firewalld restart
**關閉**
service firewalld stop
**查看防火牆規則**
firewall-cmd --list-all
**查詢端口是否開放**
firewall-cmd --query-port=8080/tcp
**開放80端口**
firewall-cmd --permanent --add-port=80/tcp
**移除端口**
firewall-cmd --permanent --remove-port=8080/tcp
**重啟防火牆(修改配置后要重啟防火牆)**
firewall-cmd --reload
**參數解釋**
1、firwall-cmd:是Linux提供的操作firewall的一個工具;
2、--permanent:表示設置為持久;
3、--add-port:標識添加的端口;
在配置文件conf/nginx.conf里進行測試
http {
upstream tomcats{
server 10.200.3.12:8081 weight=1; #加權輪詢
server 10.200.3.12:8080 weight=2;
}
server {
listen 80; #設置nginx的訪問端口
location / {
proxy_pass http://tomcats;#對應upstream tomcats 轉發地址
}
location ~ \.(gif|jpg|jpegg|png|bmp|swf|json|html|js|css)$ { # 正則表達式匹配圖片
root html; #配置靜態資源在html目錄下面找
}
}