mckeegan375
mckeegan375

Reputation: 255

URL Rewriting using .htaccess

I'm trying to get a url to rewrite using htaccess but can't seem to get it working.

I'm trying to rewrite http://website.com/pages/blog/article.php?article=blog-entry so that it can be entered as http://website.com/pages/blog/blog-entry but i'm getting an error when I try the following:

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 

RewriteRule  ^pages/blog/(.+)$   pages/blog/article.php?article=$1 [NC,L]

Can anybody see where i'm going wrong as this just gives me a 404 error. Thanks in advance.

Upvotes: 1

Views: 180

Answers (2)

Lizardx
Lizardx

Reputation: 1195

I'm trying to rewrite http://website.com/pages/blog.php?article=blog-entry so that it can be entered as http://website.com/pages/blog/blog-entry but i'm getting an error when I try the following:

RewriteEngine on  RewriteCond %{REQUEST_FILENAME} !-d  RewriteCond
%{REQUEST_FILENAME}\.php -f 

RewriteRule  ^pages/blog/(.+)$   pages/blog/article.php?article=$1
[NC,L]

Your wording is confusing, but I believe this is what you mean:

The real url is: http://website.com/pages/blog.php?article=blog-entry

you want to be able to use a 'friendly' url: http://website.com/pages/blog/blog-entry to point to the real url.

RewriteEngine on  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule  ^pages/blog/(.+)$  /pages/blog/article.php?article=$1   [QSA,L]

The first two tests ask: is this a directory that exists? is this a file that exists? Because article.php is a file, it won't be included in this action, so you won't enter into an endless loop, which is always the risk with incorrectly done rewrite rules.

Take the given url, and use query string append (QSA) to attach the desired data to the actual file that will process the request. This is not a rewrite in that the url the user sees does not change, this only happens internally in apache, which sends the request to the desired target, with the desired information.

You have to test if the file or directory exists because otherwise you'd be applying this rule incorrectly, since it should only be applied when the target does NOT exist. This is basically how all blog/cms 'search engine friendly urls' work, more or less.

Last, since the target is /blog.php?article=blog-entry you can't skip the leading /.

However, it's unclear to me why you'd want the friendly url to be so long, when you can just make it short, and friendlier: like, pages/[article-name]

Upvotes: 1

anubhava
anubhava

Reputation: 786291

Use this rule inside /pages/blog/.htaccess:

RewriteEngine on 
RewriteBase /pages/blog/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ article.php?article=$1 [QSA,L]

Upvotes: 1

Related Questions