mod_rewrite a .html to a subdomain - php

Morning everyone,
I'm really hoping someone can help. I've redeveloped a html website into a php website and I want to use mod_rewrite.
I'm probably being really stupid (as you can see though I'm very new to this!) but I promised I've googled about but can't see the answer.
What I need to do is redirect my old crappy .html files to a virtual subdomain.
So Example.html needs to go to example.mydomain.co.uk (I only have a couple of pages so I think I can get away without using expressions).
I got as close as:
RewriteEngine On # Turn on the rewriting engine
RewriteBase /
RewriteRule example.html$ ^example\.mydomain\.co.uk [R=301,NC]
but that just does mydomain.co.uk\%5eexample.mydomain.co.uk. I've found tons of examples to then push the domain to php so that bits sorted it just this first bit!
Many many thanks in advance for all your help.
Regards, Alan

If you want anything which begins with only a-z lowercase letters to be redirected to the subdomain, then this will do the trick:
RewriteRule ^([a-z]+)\.html$ $1.mydomain.co.uk [R=permanent]
However, you need to think carefully about whether there are any .html files which must not be redirected. In such cases you'll need to identify whether there is a pattern which can be easily avoided, in which case a change of the regular expression may be all that is needed. If there is no pattern which allows you to easily avoid these non-redirect pages, then you'll probably need to use RewriteCond and add checks in for each page for which you want to avoid a redirect.

Related

Is there htaccess rule to redirect two same url with different parameter on the other same url with other parameter?

I have two URLs '/cover-letters/abcd/' and '/cover-letters/abcd/amp' and want to redirect it to '/cover-letter/examples/maintenance/xyz' and '/cover-letter/examples/maintenance/xyz/amp' respectively.
Can it be done by a single htaccess 301 redirect rule? Or is there any other way to do it?
I have tried all the solutions given on StackOverflow. Please suggest the solution
Doing it in WordPress/PHP is going to give you greater flexibility and control, in general, but you have to wait for a bunch of PHP code to execute fist, which may not be good/ideal. So if it can be avoided, the .htaccess file is best for that. Your question was specially about if you could do it in .htaccess, so here is how you do that:
RedirectMatch 301 (/?)cover-letters/abcd(/?)([^/]*) $1cover-letter/examples/maintenance/xyz$2$3
However that are also some reason/scenarios where you may not want to or cannot use the .htaccess. A little off topic, but worth noting for others.
Since you tagged WordPress in your question you can also install https://wordpress.org/plugins/redirection/ . It's a very easy to use, well done plugin for redirections. I use it all the time and highly recommend it.
Edit for question in the comments
In order to test against query strings you need to use the mod_rewrite module. The mod_alias modules (used in the original answer) does not support query string lookups. You need to do the following:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^(abcd)$
RewriteRule ^(.*?)(/?)$ $1/%0 [R=301,QSD,L]

GET request without needing the ? at the end

I am developing my login system a bit further to look a lot more professional, and I wanted to know how I could turn get requests into simple links so they look a lot more sleeker?
For example for one of my systems a user can search someones elses profile by going to http://www.example.com/user?user=JimmyJones
Thats all fine and dandy but I don't think it looks very good and many other websites don't have this in their links due to some kind of trick I don't know about, as you can see I have gotten rid of the .php at the end which is done using some very simple htaccess.
But how can I change that link above to:
http://www.example.com/user/JimmyJones
Thank you very much for taking your time to read this and I really hope someone can help me out with my little problem, I assume there is some way to do this in .htaccess?
EDIT:
Here are some websites that do it just about how I would like to do it:
imgur.com/user/example
facebook.com/exampleuser
you make .htaccess file in the root dictionary then start it with
RewriteEngine on
then write your rules, For your example it would be like this
RewriteRule ^/?user/([^/]+)/?$ user?user=$1 [L,QSA]
so a full page would be like this
RewriteEngine on
RewriteRule ^/?user/([^/]+)/?$ user.php?user=$1
just for your example.
In .htaccess assuming the Apache web server with the rewrite module enabled, something like this:
RewriteEngine On
RewriteRule ^user/([a-zA-Z]+)$ user.php?user=$1 [L]
The first line says use the rewrite engine.
The second, says match a url that begins (or rather is relative to the .htaccess containing folder) with the pattern 'user' followed by a slash and matching a pattern of any alphabetic characters until the end of the string (not including additional query parameters).
The L flag basically says job done.
If the .htaccess were in the public root:
//example.com/user/JimmieJones
would map to:
//example.com/user.php?user=JimmieJones
However it will not match:
//example.com/user
//example.com/user/
//example.com/user/JimmieJones/
//example.com/user/Freddy_K9
Note that any existing links in your application:
Visit Jimmie's Profile
Would likely need to be updated. And with the example pattern above, the old style urls (previously indexed/bookmarked) could fail without your existing rule. You may need to adapt the pattern or set up redirects for the old style.
Managing lots of redirects and rewrites can become a headache. I'd advice some attention to your url name spacing. And documenting them.
I reserve first level patterns for aliases/shortcuts/campaigns.
//example.com/slug
I'd avoid that for your user profile urls if possible.
You'll ideally want to aim for consistency and have one-one correspondence for URLs(with associated http method) and resources (canonical urls).

Create a rewrite rule in .htaccess for php file

I am very new to .htaccess, I am having some problem with file action.
Example:
http://www.domain.com/upload_pic.php?action=save_pic
I wrote the .htaccess rule like
RewriteEngine On
RewriteRule ^sabc([a-zA-Z0-9!##$-_]*)$ upload_pic.php?action=$1
I want the desired result like:
http://www.domain.com/sabc/save_pic
How can I get the desired result, please correct my .htaccess line.
Change it to:
RewriteEngine On
RewriteRule ^sabc/(.+)$ upload_pic.php?action=$1
The .+ will capture one or more characters after the / and be captured into $1
There are several other guides on the web already, but to understand it in better way as you are beginner #AMY, I have writen this for you. Hope this will work for you.
Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7.
http://www.domain.com/upload_pic.php?pic_id=7
The problems with this kind of URL structure are that the URL is not at all memorable. It's difficult to read out over the phone (you'd be surprised how many people pass URLs this way). Search engines and users alike get no useful information about the content of a page from that URL. You can't tell from that URL that that page allows you to buy a Norwegian Blue Parrot (lovely plumage). It's a fairly standard URL - the sort you'd get by default from most CMSes. Compare that to this URL:
http://www.domain.com/sabc/7/
Clearly a much cleaner and shorter URL. It's much easier to remember, and vastly easier to read out. That said, it doesn't exactly tell anyone what it refers to. But we can do more:
http://www.domain.com/sabc/user-navnish/
Now we're getting somewhere. You can tell from the URL, even when it's taken out of context, what you're likely to find on that page. Search engines can split that URL into words (hyphens in URLs are treated as spaces by search engines, whereas underscores are not), and they can use that information to better determine the content of the page. It's an easy URL to remember and to pass to another person.
Unfortunately, the last URL cannot be easily understood by a server without some work on our part. When a request is made for that URL, the server needs to work out how to process that URL so that it knows what to send back to the user. URL rewriting is the technique used to "translate" a URL like the last one into something the server can understand.
To accomplish this, we need to first create a text document called ".htaccess" to contain our rules. It must be named exactly that (not ".htaccess.txt" or "rules.htaccess"). This would be placed in the root directory of the server (the same folder as "upload_pic.php" in our example). There may already be an .htaccess file there, in which case we should edit that rather than overwrite it.
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^sabc/?$ upload_pic.php [NC,L] # Handle requests for "sabc"
A couple of quick items to note - everything following a hash symbol in an .htaccess file is ignored as a comment, and I'd recommend you use comments liberally; and the "RewriteEngine" line should only be used once per .htaccess file (please note that I've not included this line from here onwards in code example).
The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:
RewriteRule - Tells Apache that this like refers to a single
RewriteRule.
^/sabc/?$ - The "pattern". The server will check the URL of every
request to the site to see if this pattern matches. If it does, then
Apache will swap the URL of the request for the "substitution"
section that follows.
upload_pic.php - The "substitution". If the pattern
above matches the request, Apache uses this URL instead of the
requested URL.
[NC,L] - "Flags", that tell Apache how to apply the rule. In this
case, we're using two flags. "NC", tells Apache that this rule should
be case-insensitive, and "L" tells Apache not to process any more
rules if this one is used.
# Handle requests for "sabc" - Comment explaining what the rule does (optional but recommended)
The rule above is a simple method for rewriting a single URL, and is the basis for almost all URL rewriting rules.
RewriteEngine On
RewriteRule ^sabc/(.+)$ upload_pic.php?action=$1
Hope this will be helpful for you to understand URL rewriting #AMY.

change url using .htaccess [domainname/cms.php?iCmsId=1 covert to domainname/about-us.php]

I need to change display of webpage url
My webpage have a url like cms.php?iCmsId=1, cms.php?iCmsId=2, cms.php?iCmsId=3 etc..
Now i want cms.php?iCmsId=1 then url will be www.test.com/about-us.php or www.test.com/about-us.html
This will redirect the user to about-us.html.
RewriteRule ^cms.php?iCmsId=1$ /about-us.html [R=301,L]
RewriteRule ^cms.php?iCmsId=2$ /about-us.html [R=301,L]
I think you are interested in this:
RewriteEngine On
RewriteCond %{REQUEST_URI} .html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^about-us.html cms.php?iCmsId=1 [PT]
This means:
activates rewrite engine
if client is requesting a html page
if the file does not exist on the server
if url is about-us.html then access cms.php?iCmsId=1
If you want to select something like
RewriteRule ^about-us-([0-9]+).html cms.php?iCmsId=$1 [PT]
This will match any url like: about-us-324.html and will actually access your page like: cms.php?iCmsId=324
Is this what you are asking?
P.S: Chris is telling you how to 301 redirect using .htaccess
One of the more powerful tricks of the .htaccess hacker is the ability to rewrite URLs. This enables us to do some mighty manipulations on our links; useful stuff like transforming very long URL's into short, cute URLs, transforming dynamic ?generated=page&URL's into /friendly/flat/links, redirect missing pages, preventing hot-linking, performing automatic language translation, and much, much more.
Make no mistake, mod_rewrite is complex. This isn't the subject for a quick bite-size tech-snack, probably not even a week-end crash-course, I've seen guys pull off some real cute stuff with mod_rewrite, but with kudos-hat tipped firmly towards that bastard operator from hell, Ralf S. Engelschall, author of the magic module itself, I have to admit that a great deal of it still seems so much voodoo to me.
The way that rules can work one minute and then seem not to the next, how browser and other in-between network caches interact with rules and testing rules is often baffling, maddening. When I feel the need to bend my mind completely out of shape, I mess around with mod_rewrite!
After all this, it does work, and while I'm not planning on taking that week-end crash-course any time soon, I have picked up a few wee tricks myself, messing around with web servers and web sites, this place..
The plan here is to just drop some neat stuff, examples, things that have proven useful, and work on a variety of server setups; there are Apache's all over my LAN, I keep coming across old .htaccess files stuffed with past rewriting experiments that either worked; and I add them to my list, or failed dismally; and I'm surprised that more often these days, I can see exactly why!
Very little here is my own invention. Even the bits I figured out myself were already well documented, I just hadn't understood the documents, or couldn't find them. Sometimes, just looking at the same thing from a different angle can make all the difference, so perhaps this humble stab at URL Rewriting might be of some use. I'm writing it for me, of course. but I do get some credit for this..
time to get dynamic, see..
RewriteRule (.*).htm $1.php
beginning rewriting..
Whenever you use mod_rewrite (the part of Apache that does all this magic), you need to do..
you only need to do this once per .htaccess file:
Options +FollowSymlinks
RewriteEngine on
..before any ReWrite rules. note: +FollowSymLinks must be enabled for any rules to work, this is a security requirement of the rewrite engine. Normally it's enabled in the root and you shouldn't have to add it, but it doesn't hurt to do so, and I'll insert it into all the examples on this page, just in case*.
The next line simply switches on the rewrite engine for that folder. if this directive is in you main .htaccess file, then the ReWrite engine is theoretically enabled for your entire site, but it's wise to always add that line before you write any redirections, anywhere.
Although highly unlikely, your host may have +FollowSymLinks enabled at the root level, yet disallow its addition in .htaccess; in which case, adding +FollowSymLinks will break your setup (probably a 500 error), so just remove it, and your rules should work fine.
Important: While some of the directives on this page may appear split onto two lines in your browser, in your .htaccess file they must exist completely on one line. If you drag-select and copy the directives on this page, they should paste just fine into any text editor.
simple rewriting
Simply put, Apache scans all incoming URL requests, checks for matches in our .htaccess file and rewrites those matching URLs to whatever we specify. something like this..
all requests to whatever.htm will be sent to whatever.php:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [NC]
Handy for anyone updating a site from static htm (you could use .html, or .htm(.*), .htm?, etc) to dynamic php pages; requests to the old pages are automatically rewritten to our new urls. no one notices a thing, visitors and search engines can access your content either way. leave the rule in; as an added bonus, this enables us to easily split php code and its included html structures into two separate files, a nice idea; makes editing and updating a breeze. The [NC] part at the end means "No Case", or "case-insensitive"; more on the switches, later.
Folks can link to whatever.htm or whatever.php, but they always get whatever.php in their browser, and this works even if whatever.htm doesn't exist! But I'm straying..
As it stands, it's a bit tricky; folks will still have whatever.htm in their browser address bar, and will still keep bookmarking your old .htm URL's. Search engines, too, will keep on indexing your links as .htm, some have even argued that serving up the same content from two different places could have you penalized by the search engines. This may or not bother you, but if it does, mod_rewrite can do some more magic..
this will do a "real" external redirection:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ http://xxxx.org/$1.php [R,NC]
not-so-simple rewriting ... flat links and more
You may have noticed, the above examples use regular expression to match variables. What that simply means is.. match the part inside (.+) and use it to construct "$1" in the new URL. In other words, (.+) = $1 you could have multiple (.+) parts and for each, mod_rewrite automatically creates a matching $1, $2, $3, etc, in your target (aka. 'substitution') URL. This facility enables us to do all sorts of tricks, and the most common of those, is the creation of "flat links"..
Even a cute short link like http://mysite/grab?file=my.zip is too ugly for some people, and nothing less than a true old-school solid domain/path/flat/link will do. Fortunately, mod_rewrite makes it easy to convert URLs with query strings and multiple variables into exactly this, something like..
a more complex rewrite rule:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^files/([^/]+)/([^/]+).zip /download.php?section=$1&file=$2 [NC]
would allow you to present this link as..
http://mysite/files/games/hoopy.zip
and in the background have that transparently translated, server-side, to..
http://mysite/download.php?section=games&file=hoopy
which some script could process. You see, many search engines simply don't follow our ?generated=links, so if you create generating pages, this is useful. However, it's only the dumb search engines that can't handle these kinds of links; we have to ask ourselves.. do we really want to be listed by the dumb search engines? Google will handle a good few parameters in your URL without any problems, and the (hungry hungry) msn-bot stops at nothing to get that page, sometimes again and again and again…
I personally feel it's the search engines that should strive to keep up with modern web technologies, in other words; we shouldn't have to dumb-down for them. But that's just my opinion. Many users will prefer /files/games/hoopy.zip to /download.php?section=games&file=hoopy but I don't mind either way. As someone pointed out to me recently, presenting links as standard/flat/paths means you're less likely to get folks doing typos in typed URL's, so something like..
an even more complex rewrite rule:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^blog/([0-9]+)-([a-z]+) http://corz.org/blog/index.php?archive=$1-$2 [NC]
Escaping:
\char escape that particular char
For instance to specify special characters.. [].()\ etc.
Text:
. Any single character (on its own = the entire URI)
[chars] Character class: One of following chars
[^chars] Character class: None of following chars
text1|text2 Alternative: text1 or text2 (i.e. "or")
e.g. [^/] matches any character except /
(foo|bar)\.html matches foo.html and bar.html
Quantifiers:
? 0 or 1 of the preceding text
* 0 or N of the preceding text (hungry)
+ 1 or N of the preceding text
e.g. (.+)\.html? matches foo.htm and foo.html
(foo)?bar\.html matches bar.html and foobar.html
Grouping:
(text) Grouping of text
Either to set the borders of an alternative or
for making backreferences where the nthe group can
be used on the target of a RewriteRule with $n
e.g. ^(.*)\.html foo.php?bar=$1
Anchors:
^ Start of line anchor
$ End of line anchor
An anchor explicitly states that the character right next to it MUST
be either the very first character ("^"), or the very last character ("$")
of the URI string to match against the pattern, e.g..
^foo(.*) matches foo and foobar but not eggfoo
(.*)l$ matches fool and cool, but not foo

URL rewriting - Beginners guide

I need to learn how to do URL rewriting for a site to get pretty URLs...
I have a general idea of how it works through the 50 tutorials I read. But none of them really clicked and never managed to make it properly work.
Do you know of any tutorials that are good for me to start?
Here is an example of how I want to use it:
Here is the basic link
http://www.dico2rue.com/dictionnaire.php?idW=675&word=Resto-basket
I want it to become like this:
http://www.dico2rue.com/dictionnaire/675/Resto-basket
But when I did that, all my links (like for CSS sheets, images,...) didn't work. Do I need to full linking (which apparently slows your site down)?
Thanks for your help.
UDPATE
There are 2 options for the links
PAGE = ?page=1
WORD = ?idW=45&word=google-friendly-url-part-here
The code in htaccess is
RewriteRule ^dictionnaire.php/p([0-9]+)?$ dictionaire.php?page=$1 [NC,L]
RewriteRule ^dictionnaire.php/([0-9]+)/([a-z])?$ dictionaire.php?idW=$1&word=$2 [NC,L]
I hope this helps.
Have a play with something like CodeIgniter, Wordpress, or Drupal. You can see how the URLs are formed and how they map to the contents of .htaccess.
This mod_rewrite cheatsheet is very useful.
Given that your stylesheets are already referenced absolutely (they include http://www.dico2rue.com/) it's probably because you're telling all your images, stylesheets and JavaScript files to go through index.php. Instead you need to tell .htaccess to leave physical files alone, and only parse other URLs.
Post what you have in your .htaccess file here and I'm sure we can help fix it.
Check if you're requesting a existing file using a (negative)RewriteCond using flags -f and/or -d. Used in many tutorials, check the topmost results at any search engine.

Categories