1

I have a setup of docker-compose having nginx and wordpress. I followed one of the tutorials across the web and everything seems to work fine.

BUT I have one critical plugin which generates a couple of html/js files directly via PHP. Meaning HTML code contains <script> tag with path to /script.js, plugin catches that particular name and respond with appropriate content. No url-rewrite modules involved here, only some self-written (i.e. from plugin)

I can't figure out how to configure nginx to allow fpm docker image to serve that server-side generated js.

Now I have the following setup:

location / {
  try_files   $uri $uri/ /index.php?$query_string;
}
location ~* \.php$ {
  fastcgi_pass wordpress:9000;
  fastcgi_index index.php;
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
location ~ ^/(script1.js|script2.js) {
  fastcgi_pass wordpress:9000;
  fastcgi_index index.php;
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
location ~* \.(css|js|gif|ico|jpeg|jpg|png)$ {
  expires max;
  log_not_found off;
}

Once I reaquest the page, script1 and script2 respond with 404.

Is this possible to achieve in general?

nKognito
  • 117
  • 6
  • 1
    Just as a test, try removing both of the last two location blocks: `location ~ ^/(script1.js|script2.js)` and `location ~* \.(css|js|gif|ico|jpeg|jpg|png)$` and see if the site works correctly albeit with the wrong `expires` value. – Richard Smith Jan 19 '20 at 13:46
  • Hey, thanks for reply @RichardSmith. It is solves the issue but this means that any JS files will be serviced by fpm as well rather then serving them statically.. – nKognito Jan 19 '20 at 13:53
  • No, that means that all non-existent JS files will be served by `index.php`. See the `try_files` directive in your config. – Piotr P. Karwasz Jan 19 '20 at 15:03

1 Answers1

1

The try_files statement will serve static files if they exist and otherwise send the request to /index.php. Because the script1.js and script2.js files do not exist, they are handled by /index.php, which is what you want.

The location ~ ^/(script1.js|script2.js) and location ~* \.(css|js|gif|ico|jpeg|jpg|png)$ blocks breaks this logic.

One solution is to remove the location ~ ^/(script1.js|script2.js) block (which is just wrong), and place a try_files statement into the location ~* \.(css|js|gif|ico|jpeg|jpg|png)$ block.

For example:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}
location ~* \.php$ {
    ...
}
location ~* \.(css|js|gif|ico|jpeg|jpg|png)$ {
    try_files $uri /index.php?$query_string;
    expires max;
    log_not_found off;
}
Richard Smith
  • 11,859
  • 2
  • 18
  • 26