首先需要搞清楚nginx本地是怎么安装配置的、然后在根据如下步骤编写bat脚本:
思路
1.下载nginx-1.26 zip压缩包安装包
2.调整conf配置
3.借助winsw将nginx应用注册为服务,winsw下载地址 然后重命名nginx_service.exe
4.配置nginx-service.xml
5.注册windows server服务
6.启动nginx
nginx.conf (最简化配置、可自定义调整)
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9000;
server_name localhost;
# 前端域名映射
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
nginx-service.xml
<service>
<id>NGINX_LINSN</id>
<name>NGINX_LINSN</name>
<description>NGINX_LINSN service</description>
<executable>C:\nginx-1.26.0\nginx.exe</executable>
<logpath>C:\nginx-1.26.0\logs</logpath>
</service>
bat脚本
@echo off
echo windows10 x64 server Nginx init
REM 请求管理员权限并隐藏窗口
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 :: & echo 执行中,请稍候... & timeout 2 > nul","","runas",0)(window.close)&&exit
setlocal enabledelayedexpansion
rem 设置 Nginx 目录变量,方便后续引用和修改
set ServiceName=NGINX_LINSN
%~d0
cd %~dp0
set CURRENT_DIR=%~dp0
set CURRENT_DIR=%CURRENT_DIR:~0,-1%
set NGINX_DIR=%CURRENT_DIR%\nginx-1.26.0
set NGINX_SERVER_DIR=%CURRENT_DIR%\nginx-1.26.0\nginx-service.exe
set NGINX_LOGS=%CURRENT_DIR%\nginx-1.26.0\logs
echo query %ServiceName% state info ...
sc query "%ServiceName%" >nul 2>&1
if %errorLevel% equ 0 (
rem 服务存在,检查服务状态
for /f "tokens=2 delims=: " %%a in ('sc query "%ServiceName%" ^| find "STATE"') do (
if /i "%%a" equ "RUNNING" (
echo Nginx server state is RUNNING...
) else if /i "%%a" equ "STOPPED" (
echo Nginx server state is STOPPED...
net start %ServiceName%
) else (
echo Nginx server state is %%a...
)
)
) else (
rem 服务不存在,初始化服务
echo Nginx-server is not exist, init server %ServiceName%
cd %NGINX_DIR%
rem 创建 XML 配置文件内容
echo ^<service^> > nginx-service.xml
echo ^<id^>%serviceName%^</id^> >> nginx-service.xml
echo ^<name^>%serviceName%^</name^> >> nginx-service.xml
echo ^<description^>%serviceName% service^</description^> >> nginx-service.xml
echo ^<executable^>%NGINX_DIR%\nginx.exe^</executable^> >> nginx-service.xml
echo ^<logpath^>%NGINX_LOGS%^</logpath^> >> nginx-service.xml
echo ^</service^> >> nginx-service.xml
rem 安装服务
echo Nginx-server start server %ServiceName%
%NGINX_SERVER_DIR% install
rem 启动服务
net start %ServiceName%
)
echo windows-server-nginx success
endlocal
REM 执行完成后自动关闭
timeout /t 2 >nul
exit
亲测有效。