How does WordPress create URLs that Apache knows about?

When you create a page in WordPress, it’s just an entry in a database table; there’s no actual file at that location. However I can create a file at that location myself and it will steal the page away from WordPress. I delete the file and it seamlessly goes back to the WordPress page.

I’m just curious about how this is achieved. Presumably some communication is happening between WordPress and Apache(?).

1

Actually there is no communication happening between Apache and WordPress. The “magic” is happening in Apache mod_rewrite rules.

For a standard WordPress installation, you have the following rules in .htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Notice this line: RewriteRule . /index.php [L]
Here, we are telling Apache to internally redirect any URL request to /index.php.

Unless: this line: RewriteCond %{REQUEST_FILENAME} !-f becomes false. That means, with adding this RewriteCond with the above RewriteRule, we are telling Apache to send all requests to /index.php, but not if it’s an existing file.

Also, when this line: RewriteCond %{REQUEST_FILENAME} !-d becomes false. That means, with adding this RewriteCond with the above RewriteRule, we are telling Apache to send all request to /index.php, but not if it’s an existing directory.

So in the end, unless it’s an existing file or an existing directory, Apache is internally sending all other requests to /index.php.

So as you see, no communication is happening between Apache & WordPress. Apache is deciding everything itself and we are telling it to do so using RewriteRule and RewriteCond directives.

Read more about mod_rewrite HERE.

Leave a Comment