Cerbion
Cerbion

Reputation: 109

How to tell mod_rewrite to only rewrite when specific urls are being entered?

I am having an issue with my .htaccess / .php files I set up my web project in a way that it's split into 3 levels:

And all three are working as expected, here's my .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?page=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1&sub=$2 [L]

I have to admit, I am not very good with the Regular Expressions for .htaccess/mod_rewrite as it is something I have done very rarely up to this point.

However my issue now is, that people dont get sent to a 404 error page if the page id (see $1) is not valid, like people can technically enter mywebsite.com/asdasdasd/ and it'll bring them (obviously) to the index.php, now my question is, can this be done some way in the .htaccess or should I just use php to check if the id they entered is valid or not? I did see that there's a thing called rewriteMap but I dont want to change the httpd.conf

Can anyone help?

Upvotes: 0

Views: 59

Answers (2)

Peter
Peter

Reputation: 16933

can this be done some way in the .htaccess or should I just use php to check if the id they entered is valid or not?

I don't think this is programming problem but logical one.

  • Apache doesn't know what pages are valid /news /contact /help etc.
  • PHP knows what pages are valid

So you have only two options

a) Specify every single possible site in .htaccess which is terrible practice

b) Check in PHP is page valid then throw 404 which is only one reasonable solution.

Upvotes: 1

Geee
Geee

Reputation: 2243

Try this code. Hope this will help you,

.htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

index.php

if (isset($_GET['url'])) {
    $url = explode('/',filter_var(rtrim($_GET['url'],'/')), FILTER_SANITIZE_URL);
    print_r($url);die();
  }

Now, in the url you will get all the url segment in the arry format.

If your url is: mywebsite.com/news/123 then output will be:

Array ( [0] => news [1] => 123 ) 

you can access and add your own logic or condition as per your need. hope this will help you.

Greetings!

Upvotes: 2

Related Questions