以80端口启动Mac上的nginx服务器
安装Nginx一部分的日志:
In the interest of allowing you to run `nginx` without `sudo`, the default
port is set to localhost:8080.
If you want to host pages on your local machine to the public, you should
change that to localhost:80, and run `sudo nginx`. You'll need to turn off
any other web servers running port 80, of course.
摘要
将通过Homebrew安装的Nginx的监听端口从默认的8080更改为80,并在系统启动时进行监听。
粗略的步骤如下:
1. 编辑 nginx.conf 文件
2. 编写使用 sudo 启动 nginx 的 shell 脚本
3. 编辑 nginx plist 文件
4. 跳过输入 sudo 密码以实现自动启动
请注意,在上述步骤4中需要root权限才能进行操作,因此需要能够以root身份进行工作。另外,假设Mac的标准httpd处于休眠状态。
似乎需要使用sudo才能在80号端口等待。
可能有些应用程序像Jenkins等会使用端口8080。请设置sudoer权限以便进行执行。
编辑nginx.conf
http { …
server {
- listen 8080;
+ listen 80;
server_name
#charset koi8-r;
…
}
编写Shell脚本
#!/bin/bash
NGINX_BIN="/usr/local/sbin/nginx"
function on_die() {
sudo $NGINX_BIN -s stop
exit 0
}
trap on_die TERM
sudo $NGINX_BIN $@ &
wait
请给 `/usr/local/bin/nginx_with_sudo` 设置可执行权限,使用命令 `chmod +x`。
编辑 plist 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
…
<key>KeepAlive</key>
<false/>
+ <key>UserName</key>
+ <string>USER_NAME</string>
<key>ProgramArguments</key>
- <array>
- <string>/usr/local/opt/nginx/sbin/nginx/
- <string>-g</string>
- <string>daemon off;</string>
- </array>
+ <array>
+ <string>/usr/local/bin/nginx_with_sudo</string>
+ </array>
…
</dict>
</plist>
编辑sudoers文件
以 root 身份登录并输入 sudo su 命令。
使用 visudo 命令开始编辑 sudoers 文件。
在以sudo权限运行Nginx和脚本时,跳过密码输入。
Cmnd_Alias NGINX=/usr/local/sbin/nginx
Cmnd_Alias NGINX_SCRIPT=/usr/local/bin/nginx_with_sudo
Your_User_Name ALL=NOPASSWD: NGINX, NGINX_SCRIPT
不需要密码:所有(NOPASSWD: ALL)似乎可以指定一些方便的选项,但我认为那样的漏洞太大了,所以还是让我们一个一个地明确指定吧。
最后,如果您执行或重新启动了创建的脚本,nginx 应该会在端口 80 上启动。
让我们在 http://localhost:80/ 上进行确认。
链接
-
- qiita.com – osx の nginx を 80 番ポートで launchctl から起動する
-
- sudoでパスワードを渡す – ぶろ〜ぐ(仮称
- Man page of VISUDO
-
- What is $* and $# in Linux? – Superuser
- シグナルと trap コマンド – UNIX & Linux コマンド・シェルスクリプト リファレンス