Question

Apache Rewrite Rules

Asked by: matt_v

Hello,
I need some help with a Rewrite rule, please. :)

I am working on a client site...that was originally not setup properly, so I moved allot of stuff around and changed allot of urls in the process.

Sites (incl Google) that used to point to http://www.example.com/blog/archives/1550 now come to 404 error page that I setup.

I need to send everything linking to www.exmp.com/blog/xxxx to be redirected to www.exmp.com/xxxx.

So take the domain name and the trailing xxx, put them together and go there instead of the original request.

I need to accomplish this w/o interfering with the directives that I have already put in the .htaccess file.  All the stuff that I have in there right now refers to issues regarding security, as you will see.

I have tried a few different things like:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -!-f
RewriteCond %{REQUEST_FILENAME} -!-d
RewriteRule (.*) ^/blog/$ http://www.exmpl.com/$ [R=301,L]

etc, etc, but I really don't know what I'm doing neither do I know how the code I'm trying trying to add is affecting what I already have in there. All I can tell you is, all that I have been able to accomplish are a couple of endless loops and some 500 errors.

However, the code that you see below is working as intended right now...at least from what I can tell. If someone sees something else that I did wrong, please please let me know.

Thanks in advance.

P.S. I'm at my other "real job" right now, so my response may be a slight bit slow... :)

Options +FollowSymlinks
Options All -Indexes
 
ErrorDocument 404 /dir/dir/dir/404.php
 
AuthName "Restricted Area" 
AuthType Basic 
AuthUserFile /home/content/s/f/r/h-m/.htpasswd 
AuthGroupFile /dev/null 
<files wp-login.php>
require valid-user
</files>
<files /wp-admin/>
require valid-user
</files>
<files wp-config.php>
Order deny,allow
deny from all
</files>
 
##
## IP Controls to be implemented soon
##
## Please tell me how to limit this IP control to specific folders the way I've 
## done with the <files></files> directive above. I don't want to shutout 
## everyone from the whole site, I want to shut everyone (w/ excp listed)
## to "parts" of the site/folders, based on their IP.
##
#AuthUserFile /dev/null
#AuthGroupFile /dev/null
#AuthName "Access Control"
#AuthType Basic
#<LIMIT GET>
#order deny,allow
#deny from all
#allow from xx.xx.xx.xx
#allow from xx.xx.xx.xx
#</LIMIT>
 
 
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*http://www.example.org/.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-14 at 10:09:16ID24730255
Tags

Apache Web Server

Topic

WordPress

Participating Experts
2
Points
400
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. RewriteCond questions (.htaccess)
    Several .htaccess questions: 1) How can I add trailing slash in all cases unless a file extension is shown (or is it better to strip trailing slashes always?) 2) Do RewriteConds accumulate? My problem is that I already have a rewriterule: RewriteRule ^(.+)/from/(.+)/to/(.+...
  2. Extremely difficult RewriteCond - RewriteRule
    Hi there everyone, I am pretty new to Apache and have problems expressing the technical terms but i'll try hope I can find an answer, thanks in advance. We have just changed our web sites servers and also the address after this server change: My question is following: Goog...
  3. htaccess rewriterule
    Hi, I have an htaccess rewrite rule that forwards any request ending in .html to my login script. This works great. However if somebody comes to my site as http://www.mysite.com then it dosnt forward to the login url because there is no /index.html. How can i fix this? opti...
  4. htaccess rewriterule not
    hi, i have the following htaccess rewrite rule that rewrites any url with xml in it. how can I change the rewrite rule so it only applies if the url is not sitemap.xml? thx RewriteRule xml /feed.php [L]
  5. combine htaccess rewritecond
    Hi all, Can somebody show me how to combine the following three apache htaccess rewrite conditions into one line: RewriteCond %{REQUEST_URI} !Send\.php$ RewriteCond %{REQUEST_URI} !Receive\.php$ RewriteCond %{REQUEST_URI} !Config\.php$ Thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: caterham_wwwPosted on 2009-09-14 at 10:45:02ID: 25327638

Did you configure Wordpress not to use /blog/ anymore? Otherwise wordpress will return a 404 not found.

>  If someone sees something else that I did wrong, please please let me know.

See my comments below

# mixing +/- and non +/- options is unsupported
# do you _realy_ want to enable all options (ExecCGI, includes etc.)?
Options All
Options -Indexes
 
ErrorDocument 404 /dir/dir/dir/404.php
 
AuthName "Restricted Area" 
AuthType Basic 
AuthUserFile /home/content/s/f/r/h-m/.htpasswd 
AuthGroupFile /dev/null 
<files wp-login.php>
require valid-user
</files>
 
# there are no slashs in <files>, <files> can't match folders.
<files wp-admin>
require valid-user
</files>
<files wp-config.php>
Order deny,allow
deny from all
</files>
 
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php
RewriteCond %{HTTP_REFERER} !http://www.example.org/ [OR]
RewriteCond %{HTTP_USER_AGENT} =""
RewriteRule ^ http://%{REMOTE_ADDR}/ [R=301,L]
 
# redirect /blog/foo --> /foo
RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^index\.php$ /index.php [L]
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

 

by: DzynitPosted on 2009-09-15 at 08:42:03ID: 25336129

caterham_www probably has given you the answer you need to fix your problem. But to assist you a little, if you have moved your wordpress install to the root before you edited the url of the blog in the admin area, you will now need to use wp-login.php to correctly log back in instead of just wp-admin.

Examle: http://www.yourdomain.com/wp-login.php

Then under the main menu Settings, goto General.

Change both the wordpress address and the blog address to the correct location of your install. It will immediately log you out and make you log back in. But your pages should work correctly again with the mod rewrite you currently have in your htaccess. But remove the code you see below from your htacess file.

If you are still seeing the 404 errors, please check Settings > Permalinks. Be sure that Custom Structure is selected and you are using a permalink structure such as /%category%/%postname%/  which is what your htaccess is set up for.
caterham_www probably has given you the answer you need to fix your problem. But to assist you a little, if you have moved your wordpress install to the root before you edited the url of the blog in the admin area, you will now need to use wp-login.php to correctly log back in instead of just wp-admin.

Examle: http://www.yourdomain.com/wp-login.php

Then under the main menu Settings, goto General.

Change both the wordpress address and the blog address to the correct location of your install. It will immediately log you out and make you log back in. But your pages should work correctly again with the mod rewrite you currently have in your htaccess.

If you are still seeing the 404 errors, please check Settings > Permalinks. Be sure that Custom Structure is selected and you are using a permalink structure such as /%category%/%postname%/  which is what your htaccess is set up for.


RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php
RewriteCond %{HTTP_REFERER} !http://www.example.org/ [OR]
RewriteCond %{HTTP_USER_AGENT} =""
RewriteRule ^ http://%{REMOTE_ADDR}/ [R=301,L]
 
# redirect /blog/foo --> /foo
RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^index\.php$ /index.php [L]

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: matt_vPosted on 2009-09-15 at 09:40:36ID: 25336774

Ok, first, I want to apologize for how long it took me to reply...Sorry, I just have a very busy life.

Anyway, Yes, I did configure WP not to use /blog/ anymore, but all those links are still out there in Yahoo! and Google from where they crawled the site in the past.

Next...I put "Options +FollowSymlinks" in .htaccess because my hosting company uses FP extensions and I didn't want to corrupt the server files by turning on permalinks in WP, but maybe I didn't need that in there. I got that piece of information from the WP codex.  Btw, I don't use FP and I can't stand it, much rather use notepad!

Can you please explain to my slow self what:
Options All
Options -Indexes

actually does? Maybe then I can understand what part of it I need.

Thanks for the info about <files>, I have fixed that problem.

I also implemented the other changes mentioned, and all is working well. Now I just need to figure out something about WP. Before I changed to permalinks, a post was here: http://www.exmpl.com/blog/archives/1553

Now, my posts are here: http://www.exmpl.com/%year%/%monthnum%/%postname%-%-post_id%


So, not only has '/blog/' changed to '/' (we have corrected that with the Rewrite Rule)

'/archives/'   has changed to  '/2009/08/'

... and

name.com/xxxx/xx/post_id   has changed to name.com/xxxx/xx/postname-post_id

I now have dead links with the following structure:
http://www.exmpl.com/archives/1553  (the link actually contains /blog/ but we are stripping that off already)
we actually need to change /archives/ to /year/monthnum/  and 1553 needs to be changed to the actual new post name of: %postname%-%-post_id%

If you would rather not help with all this stuff, I can understand because you have already kinda answered my question.

 

by: caterham_wwwPosted on 2009-09-15 at 10:36:07ID: 25337267

> Can you please explain to my slow self what:
Options All
Options -Indexes

actually does? Maybe then I can understand what part of it I need.


It enables all options except MultiViews as described here: http://httpd.apache.org/docs/2.2/mod/core.html#options and disables Indexes (directory index listing) again.

Probably you don't want all options for security rasons; I'd suggest to remove both lines and replace them with

Options FollowSymLinks

This disables all otzher options and enables FollowSymLinks only (not the missing plus sign = override instead of add). FollowSymLinks is neded in order to use mod_rewrite in .htaccess files.


> name.com/xxxx/xx/post_id   has changed to name.com/xxxx/xx/postname-post_id

You can't get the postname into mod_rewrite without using a RewriteMap (access to httpd.conf needed). It is not a part of the old URL, so we can't extract the name from there. An other way would be ro "hardcode" each name, but that might result in xyz rules.

I'd suggest to rewrite to a local php script where you analyze the input URL-path (or a queryString variable passed by mod_rewrit to your script), make a database lookup to get the name, convert the name (e.g. spaces into hyphen as done by wordpress etc.) construct the full URL (with scheme+hostname to be RFC compliant) and to do a redirect from within PHP (header() function).

Options FollowSymlinks
 
ErrorDocument 404 /dir/dir/dir/404.php
 
AuthName "Restricted Area" 
AuthType Basic 
AuthUserFile /home/content/s/f/r/h-m/.htpasswd 
AuthGroupFile /dev/null 
<files wp-login.php>
require valid-user
</files>
 
# there are no slashs in <files>, <files> can't match folders.
<files wp-admin>
require valid-user
</files>
<files wp-config.php>
Order deny,allow
deny from all
</files>
 
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php
RewriteCond %{HTTP_REFERER} !http://www.example.org/ [OR]
RewriteCond %{HTTP_USER_AGENT} =""
RewriteRule ^ http://%{REMOTE_ADDR}/ [R=301,L]
 
# rewrite to a local script
RewriteRule ^blog/archives/([0-9]+)$ /lookup_archive.php?id=$1 [L]
 
# redirect /blog/foo --> /foo
RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^index\.php$ /index.php [L]

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

 

by: matt_vPosted on 2009-09-15 at 11:48:10ID: 25337957

@ Dzynit: Thank you for your response, however you are correct...I had already made the changes that you mentioned before I actually got to this point, but I am still having the problem listed below with %post_id%

@ caterham_www: Thank you for your assistance. You have definiately set me in the right direction. You gave me enough info to help me finish the rest, w/ the exception listed below.

@ both EXPERTS: I am gonna go ahead and close this question awarding the points to caterham_www, and I'm gonna move my problem listed below to a new question. If either one of you guys wants to snatch up that new question and help me code a PHP script as caterham_www mentioned...or if there is a better way to do it, you guys can help me there.

Ok, this is what I've ended up with following caterham_www's suggestions:

Options FollowSymlinks

<files> and other stuff here ... then:
##
## Redirect(s) for: /blm/ | /archives/tag/ | /archives/category/ | /archives/date/
##
RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]
RewriteRule ^archives/tag/?(.*) http://www.www.exmpl.com</SPAN>/tag/$1 [R=301,L]
RewriteRule ^archives/category/?(.*) http://www.www.exmpl.com</SPAN>/category/$1 [R=301,L]
RewriteRule ^archives/date/?(.*) www.exmpl.com [R=301,L]


I guess these would be the remaining problems:
Any url that is looking up a particular post_id e.g.:

http://www.exmpl.com/blog/archives/1223 or
http://www.exmpl.com/blog/archives/1223/comment-page-1</SPAN> etc., etc.

Thanks again for all the help/suggestions thus far. You guys are a tremendous help!

 

by: caterham_wwwPosted on 2009-09-15 at 12:11:09ID: 25338172

You should avoid issuing multiple redirects, i.e. from /blog/archives/tag/ to /archives/tag/; /archives/tag/ to /tag/. If /archives/tag/ was never out in the wild (but only /blog/archives/tag/) you should change the rewrite rule to ^blog/archives/tag/...... and put it above of the general "RewriteRule ^blog/?(.*) ....." to avoid multiple redirects for search engines (human users wouldn't care/notice).

 

by: matt_vPosted on 2009-09-15 at 13:46:05ID: 25339282

So, your saying that I should change this:
RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]
RewriteRule ^archives/tag/?(.*) http://www.www.exmpl.com/tag/$1 [R=301,L]
RewriteRule ^archives/category/?(.*) http://www.www.exmpl.com/category/$1 [R=301,L]
RewriteRule ^archives/date/?(.*) www.exmpl.com [R=301,L]

to this: ?
RewriteRule ^blog/archives/category/?(.*) http://www.www.exmpl.com/category/$1 [R=301,L]
RewriteRule ^blog/archives/tag/?(.*) http://www.www.exmpl.com/tag/$1 [R=301,L]
RewriteRule ^blog/archives/date/?(.*) www.exmpl.com [R=301,L]

RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]


What I did was this: I went out to Google and tried to check as many dead links as I could. Also, I have google custom search on my site, so I searched for words, tags and categories that I knew were on the site and just followed those links. Thats how I came up with the different RewriteRule(s).

Tell me if this update looks better.



 

by: matt_vPosted on 2009-09-15 at 13:48:09ID: 25339314

I know this, just adding the first one that we had did not fix all my dead links.

The first one we had was:

# redirect /blog/foo --> /foo
RewriteRule ^blog/?(.*) http://www.exmpl.com/$1 [R=301,L]

 

by: matt_vPosted on 2009-09-15 at 13:54:24ID: 25339384

P.S. We are only fixing links that people would come across on the search engines...

All the links on the actual site are working w/o any re-directs, so after Google and Yahoo! update their SERPS, we won't even need any of this. This is more of a temporary work-around.

 

by: caterham_wwwPosted on 2009-09-15 at 14:14:32ID: 25339606

> to this: ?

Yes. This will cause only one redirect, directly to the correct resource.

 

by: matt_vPosted on 2009-09-15 at 15:16:38ID: 25340203

Done! ...and it works!

Thank you!!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...