Created
February 11, 2014 09:52
-
-
Save happysundar/8932016 to your computer and use it in GitHub Desktop.
Rewrite rule to transform part of the path to a query string key/value pair
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RewriteEngine On | |
# | |
# This rewrite rule will change a URI from something like : | |
# http://foo.com/corpus/59/d0/400_59d022a8dcc082473fac85dbb219e724SongStream-ParadeofLights-ServerSide-640x765.png | |
# Notice this part of the URI ^^^ -- that becomes a query parameter... | |
# i.e, into http://foo.com/corpus/59/d0/59d022a8dcc082473fac85dbb219e724SongStream-ParadeofLights-ServerSide-640x765.png?width=400 | |
# | |
# | |
# This should be placed in the 'root' of the httpd.conf file. | |
# This is done so that all the VirtualHost, <Directory> level rewrites/aliases will take over. | |
# | |
# If the query string is empty.. | |
RewriteCond %{QUERY_STRING} ^$ [OR] | |
# OR doesn't contain an explicit width= parameter in its query string.. | |
RewriteCond %{QUERY_STRING} !width= | |
# Make sure that the request filename is not present | |
RewriteCond %{REQUEST_FILENAME} !-f | |
# Match the request URI against the following patterns: | |
# Match Group anything ahead of the final / (the actual file name) to %1 | |
# Match the chars following the / to a integer number (this will become the 'width' query param to %2 | |
# Ensure that there is a '_' char after the number | |
# Match and group the everything after the "_", but before the "." (the filename, sans extension) to %3 | |
# Ensure that there is a '.' char after the filename | |
# Ensure that the chars after the '.' is a allowed extension, and group that into %4 | |
# The NC flag makes sure that the match ignores case | |
RewriteCond %{REQUEST_URI} ^/(.+)/(\d+)_(.+)\.(png|jpg|jpeg|gif)$ [NC] | |
# | |
# Now, reconstruct the URI into the new format. Notice the QSA flag, which appends any other query | |
# parameters that might be present. We do want them to be passed on. Apache takes care of making sure there | |
# is only one '?' in the URI and all that. | |
# | |
# | |
# Also, notice the "PT" flag, which means 'passthrough', which allows other rules to cascade the URI. | |
# This lets things like aliases, which might be defined at the directory level, to work. | |
# | |
RewriteRule (.*) /%1/%3.%4?width=%2 [PT,QSA] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment