← Back

Install Nginx

Installs, starts and enables Nginx on boot. If it is already installed it exits without touching your configuration.

Root required

One-line run

curl -fsSL https://www.moiu.cn/scripts/nginx-install.sh | bash

Source

#!/usr/bin/env bash
# 安装 Nginx
#
# 装好即启动并设为开机自启,顺带确认默认站点可用。
# 已经装过就直接退出,不覆盖你现有的配置。

set -e

# 需要 root:下面的系统级改动都直接执行,不再逐条 sudo
if [ "$(id -u)" -ne 0 ]; then
    echo '[!] 这个脚本需要 root 权限,请用 sudo 重新运行:'
    echo '    curl -fsSL 脚本地址 | sudo bash'
    echo '    或已经下载到本地:sudo bash 本文件'
    exit 1
fi

echo '====== 安装 Nginx ======'

if command -v nginx >/dev/null 2>&1; then
    echo "[!] 已经装过了:$(nginx -v 2>&1)"
    echo '    没做任何改动。要重装请先自行卸载。'
    exit 0
fi

if command -v apt-get >/dev/null 2>&1; then
    apt-get update -qq
    apt-get install -y nginx
elif command -v dnf >/dev/null 2>&1; then
    dnf install -y nginx
else
    echo '[!] 认不出包管理器(只支持 apt / dnf)'
    exit 1
fi

systemctl enable --now nginx

echo ''
echo '====== 完成 ======'
echo "  版本:$(nginx -v 2>&1)"
echo "  状态:$(systemctl is-active nginx)"
echo '  站点根目录:/var/www/html'
echo '  配置目录:/etc/nginx/'
echo '  验证配置:nginx -t'

Download the raw file