htaccess change directory name into parameter - .htaccess

I have a domain that is used for redirects.
example.com/129dj9
It uses a 6 digit alphanumeric code. I would like to change example.com/129dj9 into example.com?code=129dj9 in order to redirect to another url.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com/([a-z0-9]{6})
RewriteRule ^(.*)$ https://example\.com?code={REQUEST_URI}
I want to ensure that the domain is example.com and also that the directory /129dj9 is a 6-digit alphanumeric code. My code isn't working at all.

No need for such a complex RewriteCond here, instead try something like that:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^/?([a-z0-9]{6})$ https://example.com?code=$1 [END]
Note: it is always preferable to place such rules in the real http servers host configuration instead of using dynamic configuration files (".htaccess") if you have access to that configuration. Above rule will work in both scenarios.

Related

A .htaccess redirect while editing the query string

I am trying to redirect to a new domain, while keeping the query string but in a modified way.
For example, I want to redirect:
http://guides.freshstoreinstant.com/fresh-store-instant/how-to-find-your-amazon-affiliate-key-secret-key
to
https://guides.freshlabs.group/search?query=how+to+find+your+amazon+affiliate+key+secret+key
So I am wanting to:
Take the last "folder" from the original URL (how-to-find-your-amazon-affiliate-key-secret-key)
Replace - with +
Append the result to https://guides.freshlabs.group/search?query= and redirect with 301
I tried a few things and know a little bit about .htaccess but this one has me stumped
UPDATE
This could be easier using a combination of .htaccess and PHP. Can I use .htaccess to rewrite all URLs to index.php, then use PHP to replace the characters and redirect?
You can do this using mod_rewrite in .htaccess. Try the following at the top of your .htaccess file:
RewriteEngine On
RewriteRule ^(fresh-store-instant)/([^/]*)-([^/]*)$ $1/$2+$3 [N]
RewriteRule ^fresh-store-instant/([^/]+)$ https://guides.freshlabs.group/search?query=$1 [R=302,L]
The first rule repeatedly rewrites the request (internally) replacing all - (hyphens) with + in the second path segment. The N (next) flag explicitly triggers the rewriting loop. This should be used with caution; as with any recursive-like behaviour, it needs to fail at some point. (NB: A + in the URL-path is simply a literal +.)
Once all the hyphens have been replaced, the second rule triggers an external redirect to the other domain, copying the second path segment (now containing +) to the query string in the target URL. (NB: A + in the query string part of the URL is seen as an encoded space by the receiving server.)
Note that this is a temporary (302) redirect. Only change to a 301 (permanent) once you have confirmed it works OK - to avoid caching issues.
Clear your browser cache before testing.
...while keeping the query string but in a modified way
There is no query string on your example source URL to "keep"? Note that the above redirect overwrites any query string that might be present on the source URL. Include the QSA on the second RewriteRule if you want to "append" the query string from the request.
UPDATE:
the first "folder" can vary (e.g. http://guides.freshstoreinstant.com/fresh-store-builder/...)
If there is a limited subset of folders then it will probably be better to explicitly name each one, in order to avoid potential conflicts with other URLs on your site. For example:
RewriteRule ^(fresh-store-(?:instant|builder))/([^/]*)-([^/]*)$ $1/$2+$3 [N]
RewriteRule ^fresh-store-(?:instant|builder)/([^/]+)$ https://guides.freshlabs.group/search?query=$1 [R=302,L]
If you make the initial directory entirely variable (such as below) then I can imagine this conflicting with existing URLs:
RewriteRule ^([\w-]+)/([^/]*)-([^/]*)$ $1/$2+$3 [N]
RewriteRule ^([\w-]+)/([^/]+)$ https://guides.freshlabs.group/search?query=$1 [R=302,L]
This is not possible using apache's rewrite module it does not support such search&replace actions. It only rewrites. If you really cannot live with the unaltered string which you probably could still split in your processing logic, then you have these options:
either introduce another rewriting layer, based on some scripting engine which accepts the unaltered string, converts it by means of normal string operations and output redirection headers
or you may be able to do something with apache's substitute module, but youneed to install and load that and it's usage is not exactly easy (did that, grumbled a lot...)
or use a strange looking but working workaround:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3+$4+$5+$6+$7+$8+$9 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3+$4+$5+$6+$7+$8 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3+$4+$5+$6+$7 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3+$4+$5+$6 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3+$4+$5 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3+$4 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2+$3 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)-([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1+$2 [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteRule ^/?fresh-store-instant/([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1 [R=301,QSA]
This rule set will work likewise in the http servers host configuration or in a dynamic configuration file (".htaccess" style file).
UPDATE:
I realized that your example string to be converted contains more than 9 tokens which is the more or less hard coded limit of back references supported by an apache http server. You could change that if you can recompile the sources, in that case the above solution is fine and can be extended up to a number of tokens you feel safe with.
If that is not an option (as typical), you need to try something like this instead:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteCond %{QUERY_STRING} (^|&)query=(.+)&|$
RewriteRule ^/?fresh-store-instant/?$ https://guides.freshlabs.group/search [R=301,QSA]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteCond %{QUERY_STRING} (^|&)query=(.+)(&|$)
RewriteRule ^/?fresh-store-instant/([^/-]*)[-]?(.*)/?$ /fresh-store-instant/$2?query=%2+$1 [N,QSD]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteCond %{QUERY_STRING} !(^|&)query=
RewriteRule ^/?fresh-store-instant/([^/-]*)/?$ https://guides.freshlabs.group/search?query=$1 [R=301,QSD]
RewriteCond %{HTTP_HOST} ^guides\.freshstoreinstant\.com$
RewriteCond %{QUERY_STRING} !(^|&)query=
RewriteRule ^/?fresh-store-instant/([^/-]*)[-](.*)/?$ /fresh-store-instant/$2?query=$1 [N,QSD]
Note: I did not test this, just wrote it down, so there might be some smaller glitch in there. It should work though. It implements a multiple rewriting strategy: it rewrites each token in a separate go, "storing" that token in a preliminary query argument. One by one the tokens are assembled until the final external redirection is performed because no more tokens to be converted are present in the request.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

How to redirect root domain to subfolder (with https) and rest of addon domains to subfolders (without https)

How to redirect root domain to subfolder (with HTTPS) and rest of other addon domains to subfolders (without HTTPS).
Currently I have this .htaccess in root which redirects with HTTPS to the-main-subfolder ok. But my other addon domain, say domain2 also gets redirected to the-main-subfolder.
I would like to redirect domain2 to the-domain2-subfolder without HTTPS.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RedirectMatch ^/$ /the-main-subfolder/
I am not sure if this code is correct as it might me using a wildcard. I got this code from searching on net but there are so many suggestions that I am confused now!
In summary: My main hosting account in root should go to https://www.domain1.co.uk/the-main-subfolder when user types in domain1.co.uk in browser and my addon domain http://domain2.co.uk should go to http://www.domain2.co.uk/the-domain2-subfolder.
You can use additional RewriteConds to define specific redirections:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^example.org$
RewriteRule ^ https://%{HTTP_HOST}/the-main-subfolder%{REQUEST_URI} [L,R=301,QSA]
RewriteCond %{HTTP_HOST} ^example1\.org$
RedirectRule ^(.*)$ /example1\.org-subfolder/$1 [L,QSA]
RewriteCond %{HTTP_HOST} ^example2\.org$
RedirectRule ^(.*)$ /example2\.org-subfolder/$1 [L,QSA]
RewriteCond %{HTTP_HOST} ^host1\.example\.org$
RedirectRule ^(.*)$ /host1\.example\.org-subfolder/$1 [L,QSA]
RewriteCond %{HTTP_HOST} ^host2\.example\.org$
RedirectRule ^(.*)$ /host2\.example\.org-subfolder/$1 [L,QSA]
I added a few examples to demonstrate the redability of explicit implementation and that you can do that for both, separate domains and hostnames (sometimes incorrectly called "subdomains"). I would always prefer such explicit notation over generic approaches since you can individually modify things, for example for testing or debugging purposes. Except if you are in a mass hosting situation obviously, then a database based approach makes sense.
Note that the redirection for what you call the "root domain" (example.org here) has a second RewriteCond now. Both conditions are AND-combined per default.
For safety you probably also want to add some more rules to redirect requests to something like https://example.org/host1.example.org-subfolder to the specific domain name, since according to your description you are limited to a single file tree in your hosting account. Same for request to http://test1.example.org/test1.example.org-subfolder/... to eliminate the literal folder name.
Oh, and a warning: the above syntax works for .htaccess style files only. If you have access to the real host configuration then you should always prefer to place such rules in there. However you need a slightly changed syntax then. .htaccess style rules are notoriously error prone, hard to debug and they really slow down the http server. They are only offered as a last option for those without access to the host configuration.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^domain1.co.uk$
RewriteRule ^ https://%{HTTP_HOST}/the-main-subfolder%{REQUEST_URI} [L,R=301,QSA]
Thanks #arkascha - Everything now works as expected with the above code. I suppose we do not need to mention so called add-on domains here at all because cPanel handles the sub-directories for them internally when we add subsequent domains on the hosting package (i.e. addon domains)!
Just to update that my previous solution partially works as it has few niggles/bugs. So went back to the drawing board and suddenly realised I was unnecessarily trying too hard!!
Deleted the old htaccess file first and followed instruction below..
The solution is already provided by cPanel in something called "Redirects" in Panel Icons.
I just had to enter everything in user interface text boxes like choose domainname = "domain1", old folder = "\", new folder = "https://www.domain1.co.uk/the-main-subfolder" - And just click create the redirect. In doing so it creates a .htaccess file itself automatically. I am sharing this below:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain1\.co\.uk$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain1\.co\.uk$
RewriteRule ^/?$ "https\:\/\/www\.domain1\.co\.uk\/the-main-subfolder\/" [R=301,L]

Using mod_rewrite to redirect .dev domains

In the Apache 2.4 docs on dynamic virtual hosts, it says:
Mass virtual hosts with mod_rewrite
Mass virtual hosting may also be accomplished using mod_rewrite, either using simple RewriteRule directives, or using more complicated techniques such as storing the vhost definitions externally and accessing them via RewriteMap. These techniques are discussed in the rewrite documentation.
I'm attempting to use mod_rewrite instead of mod_vhost_alias because I want it both ways: localhost/project and project.dev should point to the same folder, but either URL should work.
Here's my latest attempt (currently in an .htaccess), which gets me a lovely 500 error.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.dev$ [NC]
RewriteRule ^(.*)$ /%1/$1 [L,QSA]
If I do
...
RewriteRule ^(.*)$ http://localhost/%1/$1 [L,QSA]
I can access the files, but the URL changes (not what I want). I've tried a variety of permutations with and without slashes, RewriteBase, etc.
To be clear, I want project.dev/index.php and localhost/project/index.php to both be valid non-redirected references to /var/www/html/project/index.php. And I'd like to do this in a dynamic way, so I don't need to enter a new set of rules for every folder.
I'm not fixated on doing this with .htaccess - virtualhosts are ok too as long as they're dynamic and I can still access my sites using the localhost/ scheme and the other machines on the network can connect to the sample sites in the usual way (192.168.1.22/project/index.php).
Try this rule:
RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(.+)\.dev$ [NC]
RewriteRule ^(.*)$ /%1/$1 [L]

htaccess subdomain rewrite without a redirect

Using htaccess Rewrite, I want my url http://*.phoneataxi.com/ (where * is a wildcard, excluding 'www') to show in the address bar as is but get information from http://*.phoneataxi.com/test.php?c=*.
I have tried so many different things but nothing is doing exactly what I need. Most examples are redirecting the subdomain to the '/test.php' file in the address bar which I don't want to do.
I'm trying not to have to create individial subdomains and subdomain folders within my webroot.
Ideas?
I use this htaccess file to make Apache act as a proxy for another host:
IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^ghost\.pileborg\.se$
RewriteRule (.*) http://vps.pileborg.se/ghost/$1 [P]
</IfModule>
It causes all access to http://ghost.pileborg.se/ to be "redirected" to http://vps.pileborg.se/ghost/.
UPDATE (2020)
Some of the answers regarding this topic is very old and no longer work as expected.
After searching for hours on something that actually works, this is what I came up with; edit as you see fit:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ([a-z0-9]+)\.
RewriteRule ^(.*)$ - [E=BASE:%1]
RewriteCond %{DOCUMENT_ROOT}/%{ENV:BASE}/index.php -f
RewriteRule ^(.*)$ %{ENV:BASE}/index.php [L,NC,QSA]
RewriteCond %{DOCUMENT_ROOT}/%{ENV:BASE}/index.html -f
RewriteRule ^(.*)$ %{ENV:BASE}/index.html [L,NC,QSA]
Breakdown
Make sure that the rewrite module is installed and enabled on your host
first we turn the rewrite engine on and set the path-base
then isolate the subdomain - any letters/numbers before the first dot
set a variable in this runtime environment that contains the subdomain
check if the subdomain folder and index-file exists
if it does exist -then use that file as the request-handler (no redirect)
if it does not exist then the request carries on normally
Flags
The flags used here are explained here, but the ones used above are quite simple:
[L] Last rule, ignore the rest
[NC] No Case, no uppercase/lowercase restrictions
[QSA] I remember this as "Query String Attach" :D

Subdomain alias with htaccess

I have this code for managing a subdomain alias: browsing sub.domain.com it shows domain.com/fp/sub.
RewriteCond %{HTTP_HOST} ^sub\.domain\.com$
RewriteRule (.*) /fp/sub/$1
I have a lot of these subdomain to setup. Is there a way to automate this process placing some variables instead of the correct subdomain/folder name?
I tried this code with no success
RewriteCond %{HTTP_HOST} ^(sub1|sub2)\.domain\.com$
RewriteRule (.*) /fp/$1/$2
Francesco, first correcting your example, the rule should be:
RewriteRule ^(.*) fp/%1/$1 [L]
The % variables are set in the last successful cond regexp match.
Second there are lots of options if you have access to the system or vhost config, such as using Rewrite Maps or mass virtual hosts. If you don't have such access are limited to .htaccess, then you need to use one or more rules much as you are already doing. One variant is to use an existence check of the target directory, such as:
RewriteCond %{HTTP_HOST} ^(\w+)\.domain\.com$
RewriteCond %{DOCUMENT_ROOT}/fp/%1 -d
RewriteRule (.*) fp/%1/$1 [L]
Beware that if you are using a shared hosting service, that DOCUMENT_ROOT may not be properly set at rewrite execution, in which case your SHS provider will set up an environment variable to do the same, e.g. %{ENV:DOCUMENT_ROOT_REAL}. Do a phpinfo to find out. See Tips for debugging .htaccess rewrite rules for more advice on how to debug this.

Resources