htaccess random redirect to random url - .htaccess

is it somehow possible to randomly redirect purely in htaccess? (without need of php)
Something like:
rand_pool() = ['a.php', 'b.php', 'c.php']
RewriteRule ^page.php$ /rand_pool() [R=301,L]

You can use RewriteMap directive for this.
First you need to generate a map file:
## random.map -- rewriting map
randomX a.php|b.php|c.php
You can generate as many values (separated by |) as needed, however I don't know if there is any limit in apache regarding their count.
Then you define the Randomized Plain Text type of rewrite map using this file and finally use it in your rewrite rule.
RewriteMap randomMap rnd:/path/to/random.map
RewriteRule ^page\.php$ /${randomMap:randomX} [P,L]

No, this is not possible, at least not with any amount of efficiency. One might be able to abuse mod_unique_id to generate an unique id, then reduce this id to a new page, but this is at best dodgy.
Instead internally rewrite to a router page, then perform the necessary redirect on this page. When maintaining the code, it will be much more clear what you wanted to achieve with this.

Related

.htaccess and dynamically generated SEO friendly URLs

I'm trying to build a website that may be called from the URL bar with any one of the following examples:
domainname.com/en
domainname.com/zh-cn/
domainname.com/fr/page1
domainname.com/ru/dir1/page2
domainname.com/jp/dir1/page2/
domainname.com/es-mx/dir1/dir2/page3.html
These page requests need to hit my .htaccess template and ultimately be converted into this php call:
/index.php?lng=???&tpl=???
I've been trying to make RewriteCond and RewriteRule code that will safely deal with the dynamic nature of the URLs I'm trying to take in but totally defeated. I've read close to 50 different websites and been working on this for almost a week now but I have no idea what I'm doing. I don't even know if I should be using a RewriteCond. Here is my last attempt at making a RewriteRule myself:
RewriteRule ^(([a-z]{2})(-[a-z]{2})?)([a-z0-9-\./]*) /index.php?lng=$1&tpl=$4 [QSA,L,NC]
Thanks for any help,
Vince
What's causing your loop is that your regex pattern matching /index.php. Why? Let's take a look:
First, the prefix is stripped because these are rules in an htaccess file, so the URI after the first rewrite is: index.php (query string is separate)
The beginning of your regex: ^(([a-z]{2})(-[a-z]{2})?), matches in in the URI
The next bit of your regex: ([a-z0-9-\./]*) matches dex.php. Thus the rule matches and gets applied again, and will continue to get applied until you've reached the internal recursion limit.
Your URL structure:
domainname.com/en
domainname.com/zh-cn/
domainname.com/fr/page1
domainname.com/ru/dir1/page2
domainname.com/jp/dir1/page2/
domainname.com/es-mx/dir1/dir2/page3.html
Either has a / after the country code or nothing at all, so you need to account for that:
# here -------------------v
^(([a-z]{2})(-[a-z]{2})?)(/([a-z0-9-\./]*))?$
# and an ending match here ------------^
You shouldn't need to change anything else:
RewriteRule ^(([a-z]{2})(-[a-z]{2})?)(/([a-z0-9-\./]*))?$ /index.php?lng=$1&tpl=$4 [QSA,L,NC]

Create search engine friendly urls for our blog

We run a blog, and really need to tidy up the URLs using htaccess, but I am really stumped.
Example:
Working on a site, and I need to generate search engine friendly URLs
So I have the url currently as:
http://mywebsite.com/blog/read.php?art_id=11
Title of this page is:
Why do Australians pay so much for Cars ?
I need to change it to its corresponding SEF url. like so:
http://mywebsite.com/blog/Why-do-Australians-pay-so-much-for-Cars-?
The question mark is part of the title, and we could remove these if its a issue. Any suggestions please?
Also would prefer to drop the read.php portion. Need to create a rule that works across our entire blog.
They all follow the same pattern, only the art_id number changes.
(Assuming that you're using apache as a webserver)
Take a look at this answer for a very similar question: https://stackoverflow.com/a/8030760/851273
The problem here is that .htaccess and mod_rewrite doesn't know how to map page names to art_id's so there's 2 ways you can try to do this.
You can add some functionality to your read.php so that it can do a similar lookup but instead of art_id, it uses art_title or something. Essentially you'll have to do the backend lookup of a database (or wherever your articles are stored) and use the title as a key instead of the ID. This is a little messy since it's possible to have weird characters in titles such as non-ascii or reserved characters (like ? for instance), so you'll need to create a title encoder and decoder when pulling titles out of the database or when using titles to lookup an article in your database.
If you have access to the server config or vhost config, you may be able to setup a RewriteMap using an outside program (the prg type) and create a php script that does the title-to-ID lookup for you. Then you can create rewrite rules in your .htaccess that does something along the lines of:
RewriteRule ^blog/(.*)$ /blog/read.php?art_id=${title-to-id:$1} [L]
Where you are extracting the article title from your pretty URL, and feeding it through a rewrite map called title-to-id to get the art_id. Again you'll need to setup a title encoder/decoder so your titles will have the non-ascci and reserved characters dealt with.
Another thing that you can do is to stick an article ID in your pretty URLs so they look like this: http://mywebsite.com/blog/11-Why-do-Australians-pay-so-much-for-Cars. This is still pretty easy to see what the link is about, it's SEO friendly, and it bypasses the need to do title-to-ID lookups. The Rewrite Rules would also equally be simpler:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# add whatever other special conditions you need here
RewriteRule ^blog/([0-9]+)-(.*)$ /blog/read.php?art_id=$1 [L]
And that's it. Of course, you'd have to now generate all of your blog URL's to be of the form: http://(host)/blog/(art_id)-(art_title), and you'd also have to remove special characters from the title, but you don't have to worry about writing additional code to translate titles back to IDs.

htaccess to rewrite param=NUMBER into /text

I am trying to figure out how to rewrite URLs from something like this:
example.com/collection.php?collection=1
Into:
example.com/collection-name.php
I recently redesigned an e-commerce site and need to redirect the old URLs to the new ones. I've seen loads of instructions on how to use the value of collection=1 in a rewritten URL but not how to use text instead of the value. There are only 5 collection values that need to be redirected but in addition there are also old URLs that have multiple params in them that also need to be rewritten/redirected as text. I hop that made sense.
So I think I can get them all worked out if I can get the initial redirect set up.
Other/more complex old URLs look like this:
example.com/collection.php?collection=1&product=2&item=3
Which would then need to be redirected to:
example.com/collection-name/sub-collection-name/product-name.php
Not sure exactly how to go about doing this. I don't want to write line after line in the .htaccess file but I have no idea of how else to accomplish this.
Thanks in advance, I appreciate andy and all help in this matter!
EDIT------------------------------------
Here's my new rewrite condition and rule based on the info provided to me. This would be the rule for the URLs containing all the query params using 3 separate RewriteMaps.
RewriteCond %{QUERY_STRING} collection=([^&]+)&product=([^&]+)&item=([^&]+)
RewriteRule collection.php shop/${categorymap:%1}/${rangemap:%2}/${productmap:%3}\.php [R=301,L]
Please let me know if anything looks off or I missed anything. Wasn;t sure if I needed to use $1, $2, $3 for each of the query params. I'm still a NOOB with rewrites. Thanks!
Edit------------------------------------------------------
Using the following code in my .htaccess file:
RewriteCond %{QUERY_STRING} collection=([^&]+)
RewriteRule collection.php shop/${categorymap:%1}\.php [R=301,L]
My URLs that start as "example.com/collection.php?collection=1
Are being rewritten as: example.com/shop/.php?collection=1
I am a bit lost on this one. Could it be that my Redirect Maps are not being read? Or is it something else? Thanks for the help.
You want to look into using a RewriteMap. You can specify the maps you want for collection, sub-collection and products, and then look up the text for each number.
So you would define a RewriteMap in your virtualhost config with something like
RewriteMap categmap txt:/path/to/category/map.txt
Then your rewrite rule would look something like
RewriteCond %{QUERY_STRING} collection=([^&]+)
RewriteRule collection.php ${categmap:%1} [L,R]
Add more RewriteConds for your more complicated cases and make separate rules out of them. Place the more specific rules first in the file, then the more general ones.

URL Rewriting based on form input

I'm creating a frontpage for my website with a single form and input text, Google-style. It's working fine, however, I want to generate a pretty URL based on the input. Let's say, my input is called "id", and using the GET method of form, and the action defined to "/go/", on submission, the URL will be:
site.com/go/?id=whateverIType
and I want to change it to
site.com/go/whateverIType
I was thinking on Mod Rewrite, but if the user put something in the URL, like:
site.com/go/?dontwant=this&id=whateverIType&somemore=trash
I want to ignore the other variables but "id", and rewrite the rule.
What's the better way of get this done? Thanks in advance!
PS: I'm using CodeIgniter, maybe there's something I can use for it as well. I already have a controller for "go".
I'm not familiar with CodeIgniter, but you can try the following RewriteRule
RewriteEngine on
RewriteCond %{REQUEST_URI} ^\/go\/
RewriteCond %{QUERY_STRING} id=([^&]*)
RewriteRule (.*) /go/%1? [L,R]
The %1 references the regex group from the previous RewriteCond, and the trailing ? will strip the querystring from the redirected URL.
Hope this helps.
Mod_rewrite supports conditions and rules with RegEx, so you could have a rule that matched the ?id=XXXX, that would extract it from the URL (keeping the other parameters), and rewrote the URL accordingly.
However... I don't think you want to do this, because if you rewrite the URL to be /go/Some+Search+Query, you won't be able to pick it up with say, PHP, without parsing the URL out manually.
It's really tough to have custom, SEO-friendly URLs with user input, but it is technically possible. You're better off leaving in the ?id=XXX part, and instead, using mod_rewrite in the opposite approach... take all URLs that match the pattern /go/My+Search+Terms and translate that back into something like ?id=My+Search+Terms, that way you'll be able to easily parse out the value using the URL's GET parameters. This isn't an uncommon practice - Google actually still uses URL parameters for user input (example URL: http://www.google.com/search?q=test).
Just keep in mind that mod_rewrite rewrites the URL before anything else (even PHP), so anything you do to the URL you need to handle. Think of mod_rewrite as a regular expression-based, global "Find and Replace" for URLs, every time a page is called on the server. For example, if you remove the query string, you need to make sure your website/application/whatever accounts for that.
In application/config/routes.php
$route['go/(:any)'] = "go/index/$1";
Where go is your controller and index is the index action.
http://codeigniter.com/user_guide/general/routing.html
You can use something like this in your .htaccess if you aren't already:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

url rewriting an id with a string variable

trying to figure out how to rewrite this url clientside
blog.com/post/how-to-get-the-ladies
to point serverside to
blog.com/post.php?id=123
i know how to do this:
blog.com/post/123
RewriteRule ^([^/]+)/?$ post.php?id=$1 [NC,L]
but how do you replace the id string with the post title slug?
The webserver itself doesn't make this distinction and cannot translate from your "unique text identifier" to the database id. Therefore a .htaccess rule alone evaluated by the webserver will not help you. But how is it done on all those web-applications? Normally this translation is done by Joomla/Wordpress itself and it only works as long the "how_to_get_the_ladies" text is known and unique throughout the system/database.
you can add rule that go to index file like :
RewriteRule ^(.*)$ index.php?url=$1
and in this file according to the title you can show the post that request
I solved a similar problem recently. I would suggest looking into the RewriteMap directive and using an 'External Rewriting Program'.
There are some big limitations with RewriteRule in terms of maintainability and robustness. If you haven't gotten there yet you may eventually. Only simple rewriting rules can be written safely.
With a rewriteMap you can create a php or perl script, take advantage of your existing code base, and perform all the rewriting rules from a localized place in your code which easily sits in version control.
I believe you need access to the httpd.conf (or vhost) configuration file though, RewriteMaps (or some related directive) cannot be put in .htaccess files.

Resources