Is it possible to do an odd and even replacement in .htaccess to replace / in a url with = &?
In other words I have a link like so:
page/subscriber/action/manage/sortby/id
and I'm wondering if there's way to simply replace the odd numbered / with = and the even / with &?
I have some urls that are very long with lots of arguments and I don't want to have to write a specific rule for each one.
I'm trying to convert over a very large PHP script to nicely formatted urls and it would take weeks to find every possible url and argument combination.
Why don't you want to make it in PHP script itself? I think I saw this for the first time in Zend framework, but now using similar approach in my projects.
.htaccess:
RewriteEngine on
RewriteRule .* index.php
index.php
$path = $_SERVER['REQUEST_URI'];
$paths = explode('/', $path);
// Add some logic for showing the page you need. Maybe remove domain before processing
For example you can use even arguments as array keys and add argument as value for these keys.
e.g. to print paths, use
echo "<pre>";
print_r ($paths);
echo "</pre>";
You can do this with pure mod_rewrite using two rules. This solution repeatedly applies a rule to the url until nothing is left to rewrite it. This solution is limited by the amount of internal rewrite loops you allow through httpd.conf. I believe, by default, this is 10 'recursions'. This means you can rewrite up to 10 key-value pairs before you get a 500 Internal Error. If you need more of those, consider increasing the value of LimitInternalRecursion (docs) in httpd.conf. Remember that you need to restart the httpd-service for this change to be active.
If you supply an even amount of 'arguments' in the url (e.g. site.uri/a/b/c/d), it will rewrite it to site.uri/somethingcustom.php?a=b&c=d. If you supply an odd amount of 'arguments' in the url (e.g. site.uri/index.php/a/b/c/d) it will rewrite it to site.uri/index.php?a=b&c=d. In the case of an odd amount of arguments, you can have another rule that rewrites the remaining 'thing' (in my example index.php) to an actual path (e.g. site.uri/categories/a/b to site.uri/path/to/categories.php?a=b by rewriting categories to path/to/categories). Such a rule must be written after the following two rules.
The solution uses the QSA flag (query string append). This will append the supplied query string to the previous query string (which is very helpful in this case). See the docs.
RewriteRule ^(.*)/([^/]+)/([^/]+)/?$ /$1?$2=$3 [QSA]
RewriteCond %{REQUEST_URI} !^/path/to/somethingcustom\.php$
RewriteRule ^([^/]*)/([^/]*)$ /path/to/somethingcustom.php?$1=$2 [QSA]
See the mod_rewrite docs for general information about mod_rewrite.
Please note that this method requires Apache to go through .htaccess multiple times. The solution will be more efficient if the rules are put in the top of the .htaccess file and the L flag is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With