docker – nginx – proxy_pass + proxy_redirect

張石磊發表於2019-01-19

目的:使專案域名 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後配置成功了。

相關文章