1

目的:使项目域名 www.foo.test(/index.php)/controller/action 变为 www.foo.test/project/controller/action,仍然可以正常访问。(非index.php二级目录的URL重写)

背景:

           Name                          Command              State                   Ports                 
------------------------------------------------------------------------------------------------------------
laradock_docker-in-docker_1   dockerd-entrypoint.sh           Up      2375/tcp                              
laradock_mysql_1              docker-entrypoint.sh mysqld     Up      0.0.0.0:3306->3306/tcp                
laradock_nginx_1              nginx                           Up      0.0.0.0:443->443/tcp,                 
                                                                      0.0.0.0:80->80/tcp                    
laradock_php-fpm_1            docker-php-entrypoint php-fpm   Up      9000/tcp                              
laradock_workspace_1          /sbin/my_init                   Up      0.0.0.0:2222->22/tcp 

foo.conf 配置为

server {

    listen 80;
    listen [::]:80;

    server_name www.foo.test;
    root /var/www/foo/web;
    index index.php index.html index.htm;

    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }
    
    location ~ \.php$ {
        #try_files $uri /index.php =404;
        fastcgi_pass php-upstream;
        fastcgi_index index.php;
        #fastcgi_buffers 16 16k;
        #fastcgi_buffer_size 32k;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #fixes timeouts
        #fastcgi_read_timeout 600;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt/;
        log_not_found off;
    }

    error_log /var/log/nginx/laravel_error.log;
    access_log /var/log/nginx/laravel_access.log;
}

解决:

foo.conf 配置里添加

location /project {
        proxy_pass http://127.0.0.1/;
        proxy_redirect http://127.0.0.1/ /project;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

访问 www.foo.test/project/controller/action,成功。

总结:

一开始,同事给我发了一份测试服务器上的配置,

location /project {
         proxy_pass http://127.0.0.1:9000/;
         proxy_redirect http://127.0.0.1:9000/ /project;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header REMOTE-HOST $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

可我按这个配置写入我本的 nginx 的配置时,死活不行。后还想到,我自己用的docker环境(测试环境上不是),那么 127.0.0.1 根本不是我的 php-fpm容器地址。如果要连接,需要用到php-fpm的容器名称。

所以实际上,nginx容器本地地址 127.0.0.1:80 其实就是 php-fpm9000端口。

最后,删除了 proxy_pass http://127.0.0.1:9000/; 中的 9000后配置成功了。


张石磊
48 声望0 粉丝