# Linux下安裝Nginx的步驟是什么
Nginx是一款高性能的HTTP和反向代理服務器,在Linux系統中被廣泛使用。本文將詳細介紹在主流Linux發行版(Ubuntu/Debian/CentOS)上安裝Nginx的完整流程,包含源碼編譯和包管理器兩種安裝方式。
## 一、準備工作
### 1. 系統要求
- Linux操作系統(推薦Ubuntu 20.04+/CentOS 7+)
- 至少1GB可用磁盤空間
- root或具有sudo權限的用戶
### 2. 更新系統包
安裝前建議先更新系統軟件包:
```bash
# Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
# CentOS/RHEL
sudo yum update -y
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
sudo apt update
sudo apt install nginx -y
sudo yum install epel-release -y
sudo yum install nginx -y
nginx -v
# 應顯示類似:nginx version: 1.25.3
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
# Ubuntu/Debian
sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# CentOS/RHEL
sudo yum install gcc make pcre-devel zlib-devel openssl-devel
./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_gzip_static_module
make
sudo make install
創建服務文件/lib/systemd/system/nginx.service
:
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MNPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
啟用服務:
sudo systemctl enable nginx
sudo systemctl start nginx
# 啟動服務
sudo systemctl start nginx
# 停止服務
sudo systemctl stop nginx
# 重啟服務
sudo systemctl restart nginx
# 重載配置
sudo systemctl reload nginx
# 查看狀態
sudo systemctl status nginx
/etc/nginx/nginx.conf
(包管理器安裝)/etc/nginx/conf.d/
或/etc/nginx/sites-enabled/
/usr/share/nginx/html
sudo nginx -t
# 成功輸出示例:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
# Ubuntu使用ufw
sudo ufw allow 'Nginx Full'
# CentOS使用firewalld
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
在瀏覽器訪問服務器IP:
http://your_server_ip
應看到Nginx歡迎頁面。
# Ubuntu/Debian
sudo apt purge nginx nginx-common -y
# CentOS/RHEL
sudo yum remove nginx -y
sudo rm -rf /usr/local/nginx
sudo rm /lib/systemd/system/nginx.service
sudo systemctl daemon-reload
通過以上步驟,您應該已成功在Linux系統上安裝并運行Nginx服務器。建議生產環境使用包管理器安裝以獲得自動更新支持,開發環境可選用源碼編譯以獲得更靈活的定制選項。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。