Nginx rewrite rule to replace querystring question mark with underscore
In order to mirror a whole website as static HTML,
I would like to convert URLs like http://example.com/script.php?t=12
to http://example.com/script.php_t=12
.
Notice ?
in URL is being is being converted to _
.
This will allow nginx or apache to serve these files from disk as the raw HTML we obtained and saved from wget
-- one file for each URL -- rather than as a PHP file.
Is it possible to do so via Nginx URL rewriting?
Solution 1:
I got this working using try_files:
location / {
try_files "${uri}_${args}" 404.html;
}
This will try to find a file on disk named after the pattern you provided with a "_" instead of the "?".
Further configuration depends on how you saved static files like images or stylesheets. You can add a fallback trying to read them without query string form disk like so:
location / {
try_files "${uri}_${args}" $uri 404.html;
}
Solution 2:
Something along the lines:
location ~ \.php$ {
# only rewrite URL's with args
if ($args != '') {
rewrite .* "${uri}_${args}?" last;
}
}