Forum Topic: Trouble prepending to url

Forum: .htaccess Forum : Redirecting • Posted by Ethan Miller • Updated:

I want all my urls to be rewritten with a specific path and then passed through to the rest of the rewrite rules. So specifically, I want this:

/a-project

to be written as:

/projects/a-project

and then let the processing continue.

What I've tried so far is the following:

# rewrite rules
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # make site links work
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ projects/$1 [PT]
    RewriteRule (.*) index.php [L]
</IfModule>

These directives, however, caused an internal server error. The offending bit seems to be the $1 in my first rewrite rule. If I remove that so that the line looks like:

RewriteRule ^(.*)$ projects/ [PT]

then I avoid any internal server error, but of course do not have the desired result. I've looked around a bunch and it seems as though my syntax for capturing a portion of the url is correct. For example in this question:

https://stackoverflow.com/questions/13663228/prepend-to-url-using-htaccess

1 Reply to “Trouble prepending to url”

Jeff Starr
Posted by Jeff Starr

Hi Ethan,

The key to making this work is matching the desired URLs. Currently you have:

RewriteRule ^(.*)$ projects/ [PT]

Which literally matches every request and then appends it to the redirect URL. What is needed is another bit of information from the target URLs that will enable an accurate match. For example, if /a-project is always at the beginning of the request, then we could write:

RewriteRule ^/a-project/(.*) /projects/$1 [PT]

Likewise, if there is any sort of identifiable string next to the target match, such as category or tag for example, then something like this could work:

RedirectMatch 301 /category/(.*)/whatever/ http://example.com/projects/$1/