O'Reilly

WordPress’ .htaccess File Is Genius

By on  

Choosing to use WordPress was a more difficult decision that you may think. Sure, WordPress is the most used blogging software on the internet, but I'm a programmer, right? I should want to code everything myself, right? I thought that at first but I decided to try WordPress first and I've been impressed with every part of WordPress so far. One of the interesting parts of WordPress is the URL rewriting and "slug" that gets created for each post. How did they do that?

Well, I know enough about SEF (search engine friendly) links to know that an .htaccess file had to be involved so I downloaded the .htaccess file from my hosting server and saw:


RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

That's it? Yep. Basically, the flow goes as follows:

  1. We must first establish that mod_rewrite is available on the server
  2. If so, turn on mod_rewrite
  3. Set the base of all rewriting to the web root folder
  4. If the requested filename isn't a file....
  5. ....and it isn't a folder...
  6. Send the person to index.php

Once inside the index.php file, the index.php file processes the request and presents you with the page based upon the slug in the URL. Very simple .htaccess code runs a reliable WordPress blog.

Track.js Error Reporting

Recent Features

  • Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • 5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

  • Get Slick with MooTools Kwicks

    When I first saw MooTools graphical navigation, I was impressed. I thought it was a very simple yet creative way of using Flash. When I right-clicked and saw that it was JavaScript, I was floored. How could they achieve such...

Discussion

  1. I have been playing around with this in WordPress, and the only problem I am still having is that the “Next Page” link at the bottom of some pages does not work correctly. The link goes to http://domain.com/page/2/ and is supposed to use mod_rewrite to go to ./index.php?page=2 but all attempts I make to resolve this have not helped.

    I am currently trying something like:

    "RewriteRule ^/page/(\d+)/? /index.php?page=$1"
    

    What say you? Thanks for your help.

  2. Eric, do you use WordPress 2.3 + the “Permanent Redirect”-Plugin?
    I did and came upon the exact same problem. Deactivating the plugin solved this, WP2.3 will do for you with their canonical URLs now.

  3. @Eric:

    Odd, my “next page” functionality has always worked so I can’t image what the issue is. Is your regular expression working correctly?

    @Marco:

    Thanks for contributing!

  4. Yes, actually turning off permalinks solves the problem. I was really hoping to figure this out so I don’t have ?p=4 stuff.

    I don’t think my regex is working. Maybe I will try to make it more general (like \w+/page/(\d+)/?). Do I need the ^ and $ in my regex or will it be more flexible (albeit less secure)?

    • hi in my wordpress dashboar display meassage “Please make sure your .htaccess file is writeable ” what is this meaning?

  5. Setting up RewriteRules like this to push everything through one file, and processing it according to the structure of the url is a pretty common practice in most mvc frameworks. Its great for seo, and great for developing a clean mvc based site.

  6. Thanks for commenting Brad.

    I’m aware that setting up RewriteRules is the way to do things, but WordPress’ .htaccess file is so simple.

    I’d post RewriteRules I’ve written to do the same function (MVC) but I’m too embarrassed!

  7. Heres a couple .htaccess code snippets I use to tweak wordpress..

    RewriteCond %{REQUEST_URI} ^[^\.]+\.html/$
    RewriteRule ^(.*)\.html.*$ http://www.askapache.com/$1.html [R=301,L]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(feed|wp-atom|wp-feed|wp-rss|wp-rdf|wp-commentsrss)(.*)\ HTTP/ [NC,OR]
    RewriteCond %{QUERY_STRING} ^feed [NC]
    RewriteCond %{HTTP_USER_AGENT} !^(FeedBurner|FeedValidator|talkr) [NC]
    RewriteRule .* http://feeds.askapache.com/apache/htaccess? [R=307,L]
    

    And I use a ton of RedirectMatch’s

  8. Hai David

    Can you help? how to .httaccess in Local pc ??

    i am using wamp server

  9. As Brad said, this is a pretty stock-standard .htaccess file. I know that CakePHP uses exactly the same (possibly minus the RewriteBase directive) and a number of other CMSs and frameworks do also. This set of rules is all most sites need to be able to support pretty URLs and a sensible code structure.

    So yes, WP’s .htaccess is elegant in its simplicity, but it’s hardly alone!

  10. chirag: If you have AllowOverride All in you httpd.conf file then you can place the .htaccess file in the same folder you have your index.php.
    If not you either set the AllowOverride to All (Note: There might be another option to just allow the .htaccess file to work but I normally have it set to All) or add the changes in the httpd.conf

    Nice article david. I too use those lines to redirect everything to index.php in my php mvc framework :)
    Never really knew exactly what “RewriteCond %{REQUEST_FILENAME} !-f” and
    “RewriteCond %{REQUEST_FILENAME} !-d” really meant.
    Thanks for clearing that up!

  11. Do you know what it passes back to the server?

  12. @Brandon Hansen: take a look at $_SERVER[‘REQUEST_URI’] and the query.php file near all is_home etc…

  13. yes, no doubtful…mens behind WP are genius!!!

    anyway, any tutorial how to proccesing request url in wordpress, i mean in index.php?

    regards

  14. nirok

    I’ve been trying to find an answer everywhere for this but how do you get the reply box on the comments like you have here?

  15. Jonathan

    Hi,

    You look like a htaccess knowledgeable person, I have a riddle for you:

    So we’ve installed WordPress into our /blogs/ folder.

    We had an old store in the /store/ folder.

    We upgraded to WP E-Commerce and now it’s in /blogs/store/

    We want to make all the old links that go to /store/ load the new store.

    I’ve tried this but it does not work:

    RewriteRule ^store/ /blogs/store/

    or

    RewriteRule ^store /blogs/?p=123

    if 123 is the page id of store.

    • I am so poor of WordPress. I just start to learnt it 3 hours ago and now I got one problem.

      I can change Permalink to make it as a friendly URL but when I access to thoese page I got the error message that not found my pages.

      Does anyone knew about this problem, please give some guide to me.

      Thank.

    • Just refresh the page, clear the cache and then follow the links from the home page. This is probably not anything to do with .htaccess

  16. Can anyone tell me were my htaccess file is in wordpress 3.0 im getting error 500 warnings and need to add some code to it in 1&1 hosting

  17. This is beyond frustrating. None of the .htaccess examples work, and killing my root .htaccess is simply not an option. :-/

  18. OMG Thankyou! Sometimes I get htaccess issues on my sites, and the only way to fix it is to use these examples, this saved me having to get another clean example from one of my other websites! Thanks

  19. David, I’m getting an error in WP, running 3.3.1 that says:
    Your backup folder MIGHT be visible to the public. To correct this issue, move the .htaccess file from wp-content/plugins/wp-dbmanager to /home/nnnn/public_html/blog/wp-content/backup-db

    If I move my .htaccess file to the directory indicated in the error my site doesn’t work. The location of the file is actually /home/nnnn/public_html/blog/ The file permissions for .htaccess are 0644. It seems like an erroneous error message, but I’m not a programmer so I wanted to see if you have an answer.

    Great read on your .htaccess post!

    Thanks!

    Tony

  20. Franklin

    Hi David,

    I am having some troubles with my website in search and wanted to show you my .htaccess file to ask if you think it is set up ok. It differs a little from what you are showing on this page, and I admit that I do not understand how the commands work, but I know how to find files, so please tell me if this is structured properly or if it has some errors.

    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    # END WordPress

    Thanks in advance

  21. hello all. I am trying to simply change my wordpress site to my domain name without the need to type .com/wordpress. I attempted to follow what was stated on the wordpress site, but not I’ve gotten myself into a debacle and can’t even bring up my site on domainname.com or domainname.com/wordpress. Not only that, I can’t even get to my WordPress home page!
    here is my htaccess file. I’ve been widdling away so it may look crazy…

    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{HTTP+HOST} ^www\.GlazingShopDWGs\.com/wordpress
    RewriteCond %{www\.GlazingShopDWGs\.com} !-d
    RewriteRule . cgi-bin/wordpress/index.php [L]

    # END WordPress

    can someone please put this into terms I can understand?!

    In my root directory, I’ve got 2 files of interest: root/wordpress and root/cgi-bin/wordpress

    I don’t understand the need for both or how they got there.

    I’m dealing with index.php and htaccess and I don’t know which folder to direct them to or what they do in the first place.

    I’ve spent a week on this and all I want to do is get my site back and start my company.

    ANY HELP WOULD BE APPRECIATED!

  22. # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{HTTP+HOST} ^www\.GlazingShopDWGs\.com/wordpress
    RewriteCond %{www\.GlazingShopDWGs\.com} !-d
    RewriteRule . cgi-bin/wordpress/index.php [L]

    # END WordPress

  23. Hi David, can I use .htaccess to stop direct access to wp-content directory?

  24. Since 1980, we at Bradshaw Plumbing have been building a reputation as a family owned, family operated Pompano Beach plumbing company you can rely on for dependable plumbing service and value.

  25. komal

    I have problem in htaccess rewrite rule? i want to show wordpress pages as .html
    backend i have postname structure in permalink..
    so,my pages will be come as
    http://www.abc.com/about/
    & i want be http://www.abc.com/about.html

    Any Idea???

  26. I want do change in .htaccess file. Can you tell me where can I find this file?
    Thanks in advance.

    • @Priyank Pandey

      If you use cpanel, you can use file manager.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Loading Static Templates for Intern Testing

    I use Intern by SitePen for all of my JavaScript functional testing.  Intern has loads of features other functional test frameworks don't and it's completely Promise-based -- something I got very used to when I used the Dojo Toolkit every day. Async test creation can...

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...