Jamie
Jamie

Reputation: 95

How to properly redirect multiple URLs with .htaccess

Here's what I have in my htaccess right now:

Options +FollowSymlinks
RewriteEngine on
RewriteBase /themelink/mytheme
RewriteRule ^(.+)$  http://portal.example.com/aff.php?aff=$1&p=mytheme.php [R=301,NC]

I have this .htaccess located in the /themelink/mytheme directory.

What this does is redirect someone that goes to http://example.com/themelink/mytheme/123456 to the URL http://portal.example.com/aff.php?aff=123456&p=mytheme.php

This is almost what I'm trying to do, but it's not quite where I want it yet.

What I would prefer to do is put the .htaccess in my themelink directory and have it recognize whatever folder name came after it in the URL without me having to create an individual folder for each theme.

For example, here's a few sets of links that I would like to work:

http://example.com/themelink/new-theme/5643434 ---> http://portal.example.com/aff.php?aff=5643434&p=new-theme.php

http://example.com/themelink/bloggertheme/254543 ---> http://portal.example.com/aff.php?aff=254543&p=bloggertheme.php

http://example.com/themelink/test-theme/4353663 ---> http://portal.example.com/aff.php?aff=4353663&p=test-theme.php

I can technically do this by just creating a new directory for each theme that I need a redirect setup for and just use the .htaccess above, but I would prefer to have a single .htaccess that will just work with all of them.

Hope this makes sense, please feel free to let me know if any clarifications are needed.

Upvotes: 1

Views: 473

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270599

If I am understanding correctly, you may move the .htaccess up a level into the /themelink directory, and modify it to include two () capture groups, the first capturing everything up to the first / encountered, and the second capturing everything afterward.

# .htaccess in /themelink
Options +FollowSymlinks
RewriteEngine on
# Change the RewriteBase (it actually isn't even needed)
RewriteBase /themelink
# $1 is the theme name, $2 is the aff value
RewriteRule ^([^/]+)/(.+)$  http://portal.example.com/aff.php?aff=$2&p=$1.php [R=301,NC]

The expression ([^/]+) matches one or more characters that is not a / and captures it as $1.

Now, I notice that the aff value in all your examples is numeric. If that is to be the case, I would recommend making the rewrite a little more specific to match numbers there instead of (.+) which matches anything. That way, an invalid URL (something other than numbers) won't redirect, and instead can respond with a 404.

# Ensure $2 is an integer with `\d+` (one or more digits)
RewriteRule ^([^/]+)/(\d+)$  http://portal.example.com/aff.php?aff=$2&p=$1.php [R=301,NC]

Upvotes: 2

Related Questions