2

I have a dynamically created file start.js.php?c=21 and I would like to rewrite it's extension (to start.js, with query params).

  1. Is that possible?
  2. Is that a good method having such a rewrite?
  3. Is wrong having query string ?c=21 on file location (to populate from PHP file with given c attribute)?

I am trying to create rewrite with:

server {
    location ~ \.js.php$ {
        rewrite ^(.*)$ $1.js last;
    }
}

This is returning 404 error code.

4

If the underlying filename is script.js.php then it doesn't make sense to rewrite this to script.js - as that would result in a 404.

However, the directives you posted would seem to result in a 404 for a different reason, as they rewrite script.js.php to script.js.php.js.

Presumably, you want to link to script.js?c=21 and internally rewrite this to script.js.php?c=21 (the underlying file), thus hiding the .php file extension from users. In which case, try something like the following instead:

server {
    location ~ \.js$ {
        rewrite (.*) $1.php last;
    }
}

To answer your specific queries:

  1. Is that possible?

Yes, but the "reverse" is probably what you really want to be doing. (?)

  1. Is that a good method having such a rewrite?

It's OK. Presumably, you have a requirement to mix PHP and JavaScript?

  1. Is wrong having query string ?c=21 on file location (to populate from PHP file with given c attribute)?

I don't think there is necessarily anything wrong with this. Bear in mind that some caching proxies may ignore the query string, but I think that is mostly historic.

  • You should use rewrite...last as the .php URI needs to be processed in a different location. – Richard Smith Oct 26 '18 at 19:04

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.