Reputation: 357
I'm using Rewrite Rule in htaccess to get page data by slug.
I'm doing it manually by adding lines to .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !www\.example\.co\.il$ [NC]
RewriteRule ^(.*)$ http://www.example.co.il/$1 [L,R=301]
ErrorDocument 404 /404.php
RewriteRule ^עמוד-מסוים$ /page.php?id=1 [L]
RewriteRule ^דוגמא-לעמוד$ /page.php?id=2 [L]
RewriteRule ^דוגמא-נוספת$ /page.php?id=3 [L]
RewriteRule ^טקסט-כלשהו$ /page.php?id=4 [L]
RewriteRule ^צרו-קשר$ /contact.php [L]
RewriteRule ^blog$ /blog.php [L]
It's work good but I need to add new .htaccess line every time.
my DB table has Id and Slug (and other info) and my page.php use $_GET['id'] and then select the other data from DB by this ID.
I tried somthing like this:
.htaccess:
RewriteRule ^page/([^/]*)$ /page.php?id=$1 [L]
page.php:
$id=$_GET['id'];
if(is_int($id)==false){ // if slug was enterd
$result=$mysqli->query("SELECT `id` FROM `pages` WHERE `slug`='$id' limit 1");
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
}//query
}
But the URL not look like I want (adding /page/ to url)
I tried that also:
.htaccess:
RewriteRule ^/([^/]*)$ /page.php?id=$1 [L]
but it's make problem with other url's on my site (that are not connected to page.php)
How can I make it work without adding htaccess line every time?
EDIT: when I try this .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !www\.example\.co\.il$ [NC]
RewriteRule ^(.*)$ http://www.example.co.il/$1 [L,R=301]
ErrorDocument 404 /404.php
RewriteRule ^/?([^/]+)$ /page.php?id=$1 [L]
RewriteRule ^צרו-קשר$ /contact.php [L]
RewriteRule ^blog$ /blog.php [L]
I get error on all pages, If I moving up the RewriteRule ^/?([^/]+)$ /page.php?id=$1 [L] only the page.php file will work good (blog and contact will not work) and also non-WWW url's will not work good.
Upvotes: 0
Views: 2008
Reputation: 357
Found the soultion. This working perfect:
ErrorDocument 404 /404.php
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteRule ^צרו-קשר$ /contact.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([^/]+)$ /page.php?id=$1 [L]
Upvotes: 0
Reputation: 143896
You could try adding some conditions, something like:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([^/]+)$ /page.php?id=$1 [L]
to filter out all existing files and directories.
Also, you might want to consider sanitizing your $id parameter before you stick it in a query
Upvotes: 0