目录结构
/data/
├── nginx/                    # Nginx 主目录
│   ├── sbin/nginx           # 可执行文件
│   ├── conf/                # 配置文件
│   │   ├── nginx.conf       # 主配置文件
│   │   └── sites-enabled/   # 启用的网站配置
│   ├── html/                # 网站文件
│   ├── logs/                # 日志文件
│   │   ├── access.log
│   │   └── error.log
│   ├── ssl/                 # SSL证书
│   └── cache/               # 缓存目录
├── www/                     # 网站根目录
│   ├── site1.com/
│   └── site2.com/
└── backup/                  # 备份目录

1. 创建目录结构
# 创建所有需要的目录
sudo mkdir -p /data/{nginx,www,backup}

# 创建 nginx 子目录
sudo mkdir -p /data/nginx/{conf,sbin,html,logs,ssl,cache}

# 设置权限(让当前用户有权限)
sudo chown -R $USER:$USER /data/
sudo chmod -R 755 /data/


2. 安装依赖
# CentOS/RHEL
sudo yum install -y wget gcc make pcre-devel zlib-devel openssl-devel

# Ubuntu/Debian
sudo apt update
sudo apt install -y wget gcc make libpcre3-dev zlib1g-dev libssl-dev

3. 下载 Nginx 源码
cd /data/
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz

4. 配置编译选项
cd /data/nginx-1.24.0

# 完整的配置,安装到 /data/nginx
./configure \
    --prefix=/data/nginx \
    --sbin-path=/data/nginx/sbin/nginx \
    --conf-path=/data/nginx/conf/nginx.conf \
    --pid-path=/data/nginx/logs/nginx.pid \
    --lock-path=/data/nginx/logs/nginx.lock \
    --error-log-path=/data/nginx/logs/error.log \
    --http-log-path=/data/nginx/logs/access.log \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_stub_status_module \
    --with-http_realip_module \
    --with-http_gzip_static_module \
    --with-http_sub_module \
    --with-stream \
    --with-stream_ssl_module \
    --with-threads \
    --with-file-aio \
    --with-http_auth_request_module

5. 编译和安装
# 编译(使用多核加速)
make -j$(nproc)

# 安装
sudo make install

# 验证安装
ls -la /data/nginx/

6.创建服务文件
sudo vim /etc/systemd/system/nginx.service

7 添加以下内容(针对 /data/ 目录)
[Unit]
Description=Nginx Web Server - /data/nginx
After=network.target

[Service]
Type=forking
PIDFile=/data/nginx/logs/nginx.pid
ExecStart=/data/nginx/sbin/nginx
ExecReload=/data/nginx/sbin/nginx -s reload
ExecStop=/data/nginx/sbin/nginx -s quit
PrivateTmp=true
User=$USER
Group=$USER
WorkingDirectory=/data/nginx

# 安全配置
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/data/nginx/logs /data/www
ReadOnlyPaths=/data/nginx/conf /data/nginx/html

# 资源限制
LimitNOFILE=65536
LimitNPROC=512

[Install]
WantedBy=multi-user.target
注意:把 $USER 替换为您的用户名,或者使用 nginx 用户

8.启用服务
# 重新加载 systemd
sudo systemctl daemon-reload

# 启动 nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

# 查看状态
sudo systemctl status nginx
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐