Keith Yeoh
Keith Yeoh

Reputation: 730

Docker - NGINX Container forward to PHP-FPM Container

I am running NGINX, PHP-FPM and DB in separate container.

Docker

Inside PHP-FPM is mounting a Laravel project from my local machine.

I've successfully forward the PHP request to PHP-FPM container (port 9000) while accessing 127.0.0.1:8000. Unfortunately, the requests with assets extension (e.g. .css, .js) has ran into 403 forbidden.

enter image description here

Following are my NGINX configuration script.

server {
    listen 80;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass fpm:9000;
        fastcgi_param SCRIPT_FILENAME /app/public$fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~* \.(css|js|gif|ico|jpeg|jpg|png)$ {
        fastcgi_pass fpm:9000;
        fastcgi_param SCRIPT_FILENAME /app/public$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

The request and response header for app.css file. enter image description here enter image description here

Not sure if anyone has ran into similar problems and have solution for this?

Upvotes: 2

Views: 2139

Answers (1)

Duc Trung Mai
Duc Trung Mai

Reputation: 2608

You're forward everything to PHP FPM, meanwhile, by default in PHP-FPM process config file, it only allows .php file to be served.

You can check in /usr/local/etc/php-fpm.d/www.conf inside php-fpm container, and search for security.limit_extensions, you'll see.

So here you have 2 solutions

Solution 1: map your project source into container where you're running Nginx, like this:

# docker-compose.yml

webserver:
    image: nginx:1.17-alpine
    restart: unless-stopped
    ports:
      - "8000:80"
    volumes:
      - ./:/var/www/html

By doing this Nginx can easily find your static files and serve them. Note that /var/www/html is your root project path which you defined in your Nginx config file. For example, Nginx config file for Laravel project usually looks like:

server {
    listen 80;
    index index.php index.html;

    root /var/www/html/public;
    ...

Solution 2: add .css, .js to PHP-FPM process config file, with this solution, you'll override PHP-FPM config file and add your static files to list file extensions that PHP-FPM allows. Check my demo here. This solution won't require you to map your project into Nginx container. But in reality it's not good for production like solution 1

Upvotes: 3

Related Questions