SUB0DH
SUB0DH

Reputation: 5240

How to make RewriteRule work only if URL contains specific string?

I need to add RewriteRule which works only if there is a certain string in the URL, otherwise I need to load the content from another folder. If the URL contains the string test, I need to send it to index.php as a parameter, else the content should be loaded from the directory folder.

For example: The root folder of the project is new_project. If the URL is http://localhost/new_project/test/something/, then I need to send test/something/ to index.php as parameter. Else if the URL is something like http://localhost/new_project/something/, then I need to load the content from directory/something folder.

Following is the .htaccess file I've written so far:

Options +FollowSymLinks
RewriteEngine on

# Force Trailing Slash
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

# Send request via index.php (again, not if its a real file or folder)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

# Serve other requests from the directory/ folder
RewriteRule ^(.*)$ directory/$1 [L]

What needs to be changed in the above .htaccess file so that the occurrence of test string in the URL passes the string after the string test along with the string test to index.php and if the URL doesn't contain the string test then loads the content from the directory folder?

Upvotes: 0

Views: 5716

Answers (1)

ojrask
ojrask

Reputation: 2828

You can test for the test/ inside the RewriteRule itself. Place the more specific rewrite rule before the "catch-all" directory/ rewrite rule.

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

# All requests starting with `test/` go to index (without the `test` part).
RewriteRule ^test/(.*)$ index.php?/$1 [L] # Not sure how GET parameters starting with `?/` behave.

# All others go to directory. Assuming not a valid file or dir.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ directory/$1 [L]

Upvotes: 1

Related Questions