最近研究了一下macOS系统,有点上头。另一方面又需要经常测试网页,所以决定在macOS上配一套类似网页服务器的本地环境。这里出于个人习惯,我使用的是nginx+php+mysql的配置。
安装:
在macOS上,我们可以用Homebrew完成所有组件的安装。
首先,我们要安装XCode for the command line tools:
xcode-select --install
安装完成后,安装Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Homebrew安装过程是自动完成的,完成后,我们就可以利用它来安装组件了:
对于测试网页来说,我们有必要安装OpenSSL:
brew install openssl
然后安装mysql:
brew install mysql brew services start mysql brew services list
以上三行指令将安装mysql,启动相关服务,并检查服务是否正常运行。注意:与服务器安装不同,安装过程中将不会弹出任何配置提示,所以我们需要在安装结束后单独进行设置。
打开 /opt/homebrew/etc/my.cnf
,按需要添加以下parameters:
sql_mode = "ONLY_FULL_GROUP_BY,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
然后我们修改数据库的密码,运行:
mysql_secure_installation
随后输入一至少8位的密码,然后回车,并键入y,然后再次确认。设置完后重启服务:
brew services restart mysql
接下来安装php:
brew install php
Homebrew会默认安装版本库中最新的php版本(截止目前是php@8.0
安装完成后打开配置文件 /opt/homebrew/etc/php/8.0/php-fpm.d/www.conf
将user修改为你mac本地用户名,监听端口可以根据需求保留或修改,但随后所有php相关设定均需使用此端口设定。
然后重启php相关服务,并检查服务运行情况:
brew services restart php sudo lsof -Pn | grep php-fpm
然后安装nginx:
brew install nginx
安装完成后,运行:
brew services start nginx
打开浏览器,输入 127.0.0.1:8080
,如果看到了nginx的欢迎界面,即说明nginx安装成功。
然后我们来修改一下默认的nginx配置文件 /opt/homebrew/etc/nginx/nginx.conf
其中,我们需要修改的是:
在http中加入
client_max_body_size 128M; server_names_hash_bucket_size 64;
将server中的
listen改为80,
server_name改为你想访问的域名地址,如test.x ,
添加必要的安全性header:
add_header X-Frame-Options "SAMEORIGIN"; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options "nosniff";
添加字体格式
charset utf-8;
找到server中的php设置,并修改为:
location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_split_path_info ^(.+\.php)(/.+)$; }
最后,在server中添加:
root /opt/homebrew/var/www/html; index index.php index.html index.htm;
并删除原 location / { ... }
的内容,实测如果把html目录放在这里面,网站会运行,但是php不能正常工作。
如果有添加其他server blocks的需要,则按类似:
server { listen 80; server_name your_desired_domain; add_header X-Frame-Options "SAMEORIGIN"; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options "nosniff"; charset utf-8; root your_html_directory; index index.php index.html index.htm; location / { } location ~ ^/(doc|sql|setup)/ { deny all; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_split_path_info ^(.+\.php)(/.+)$; } location ~ /\.ht { deny all; } }
然后保存退出,并更新nginx,注意此时必须使用sudo,否则会报错 nginx: [error] open() "/opt/homebrew/var/run/nginx.pid" failed
sudo nginx -t sudo nginx -s reload
最后,更新系统的hosts文件/etc/hosts
,添加
127.0.0.1 (tab) your_domain
与服务器不同的是,每一个server block都要添加一个hosts条目,就算是同一个domain。
然后打开浏览器输入你的网址就可以访问了。如果遇到你设置了奇奇怪怪网址被Safari自动跳转到google搜索的情况,就输入http://加你的网址即可。
另外补充一个小tip:
如果nginx的配置文件中root路径有空格,不要使用unix的路径(\ ),而是用””括起来正常输入空格的路径,如:
root "/Users/name/Library/Mobile Documents/..."
https相关配置还未更新。。。