1、原由
只有一个域名,以前用php编写的网页又不能放弃,考虑将其移至二级目录下,例如:
https://abc.com/html
2、运行环境
Linux服务器上,用docker容器。Nginx和php-fpm各自运行在不同的容器中,Nginx在前端负责接收http请求,将其分发到后面不同的服务容器中。收到PHP网页请求就交给php-fpm解析,php-fpm的端口是9000。
3、Nginx配置
3.1 如果使用根目录
如果php网页在根目录下就比较简单,用下面配置即可:
server {listen 80;server_name abc.com;root /usr/share/nginx/html;index index.html index.htm index.php;location / {try_files $uri $uri/ /index.php?$query_string;location ~ \.php(.*)$ {root /var/www/html/phpmy;fastcgi_pass 172.17.0.1:9000; #php容器的IP地址fastcgi_index index.php;fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;fastcgi_param PATH_INFO $fastcgi_path_info;fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;include fastcgi_params;}}
}
3.2 将php网页放在二级目录
将3.1的方法直接移植过来是行不通的,先放结果,正确的配置文件如下:
location /html {alias /var/www/html/; #PHP文件在php-fpm容器中的目录index index.php index.htm index.html;try_files $uri $uri/ /html/index.php?$query_string;if (!-e $request_filename) {rewrite ^/html/(.*)$ /html/index.php?$1 last;break;}location ~ \.php(.*)$ {fastcgi_pass 172.17.0.1:9000; # PHP容器的IP地址fastcgi_index index.php;fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;fastcgi_param SCRIPT_FILENAME $request_filename;include fastcgi_params; }location ~* \.(htm|html|jpg|jpeg|png|gif|ico|js|css|map)$ {root /usr/share/nginx/; # 静态文件目录比真实目录少一级,访问时会自动加上url的子目录} }
与在根目录下的情况不同,传给 location /html的目录是PHP文件在php-fpm容器中的目录。php-fpm接收的SCRIPT_FILENAME是 $request_filename
- 下面一段是解决页面跳转后不能正确定位问题:
if (!-e $request_filename) {rewrite ^/html/(.*)$ /html/index.php?$1 last;break;}
- 这个location是解决非php文件不能访问的问题:
location ~* \.(htm|html|jpg|jpeg|png|gif|ico|js|css|map)$ {root /usr/share/nginx/; # 静态文件目录比真实目录少一级,访问时会自动加上url的子目录}
目前这个配置文件还是有一些问题,比如直接访问目录时不能直接跳到index.php文件,访问时必须这样:
https://abc.com/html/index.php