fightstarr20
fightstarr20

Reputation: 12568

Windows 10 Xampp Apache - htaccess rewriterule not working

I am using apache XAMPP on Windows 10 and am trying to get htaccess working. I have this so far...

RewriteEngine On
RewriteRule ^noexist/?$ /folder/

I want someone to go to

www.mysite.com/noexist/test.php -> www.mysite.com/folder/test.php

But I still want the URL to be www.mysite.com/noexist/test.php

I am just getting a 404, where am I going wrong? I have confirmed the htaccess file is being loaded by putting invalid code in and it throws an error so I am certain the file is being used.

Upvotes: 1

Views: 437

Answers (1)

MrWhite
MrWhite

Reputation: 45829

RewriteRule ^noexist/?$ /folder/

The regex ^noexist/?$ matches noexist or noexist/ only, so /noexist/test.php is ignored by this rule. It also only rewrites to /folder/ only.

In other words, this rewrites /noexist (or /noexist/) to /folder/ only.

To rewrite /noexist/<something> to /folder/<something> then you need to capture the <something> part and pass this through to the target URL (i.e the substitution string). For example:

RewriteRule ^noexist/(.*) /folder/$1 [L]

The $1 backreference in the substitution string contains the URL-path captured by the parenthesised subpattern (ie. (.*)) in the RewriteRule pattern.

Don't forget the L (last) flag. (This is important if you have other directives later in the file.)

Note that this rewrite is unconditional, regardless of whether /folder/<something> exists or not. If you want to check that /folder/<something> exists before rewriting then add an additional condition. For example:

RewriteCond %{DOCUMENT_ROOT}/folder/$1 -f
RewriteRule ^noexist/(.*) /folder/$1 [L]

This assumes your .htaccess file is located in the document root.

Upvotes: 2

Related Questions