Reputation: 1320
I'm at few hours looking a various tuts on mod_rewriting, but anything I try myself never seems to work. What I'm hoping for is that I can give you guys the URL model, and get a working Rule and a breakdown of that Rule in return (I'm reasonably familiar with regex). That way I can adapt to future requirements also.
The structure is:
domain.com/contents/page.php?id=123&u=page-slug
What I want is for the user to type:
domain.com/page-slug
and be successfully redirected to the page in question.
From what I have read, this shouldn't affect PHP GET's - is this correct? Even if the id isn't actually in the address bar (obv. question, but I'm completely new to this)? It's surprising what tutorials leave out...
Thanks in advance!
Upvotes: 0
Views: 188
Reputation: 9539
If the ID is necesary then it will need to be present in the pretty url i.e. something like domain.com/page-slug/page-id
.
To rewrite this to page.php
add the following to your .htaccess in the root directory of domain.com
as below
RewriteEngine on
RewriteBase /
#if not a file or a directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# rewrite requests of the form domain.com/page-slug/123
RewriteRule ^([-a-zA-Z0-9]+)/([0-9]+)/?$ contents/page.php?id=$2&u=$1 [NC,L,QSA]
If you want to learn more see this list of .htaccess and mod_rewrite resources on the web
Upvotes: 1
Reputation: 41944
From what I have read, this shouldn't affect PHP GET's - is this correct? Even if the id isn't actually in the address bar (obv. question, but I'm completely new to this)?
If there is no id in the url, PHP GET won't get an id. But in the code you give it will work. Because you set a fixed id in the htaccess, the id will always be 123.
And why does it never seems to work? get you a error, a apache error, or...? Have you add the mod_rewrite module to the httpd.conf? If not:
Browse to you httpd.conf file and open it in your editor. Look in the file for:
#LoadModule rewrite_module modules/mod_rewrite.so
Remove the #
in the front of the line, save the file and restart apache.
Your .htaccess file should look like:
RewriteEngine On
RewriteBase /
RewriteRule ^(\d*?)/(.*?)$ page.php?id=$1&u=$2
Then it replace domain.com/id/page-slug to domain.com/page.php?id=id&u=page-slug
Upvotes: 0