Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

.htaccess rewriting URLs that don't exist

Currently, I'm working with some guys that love short URLs for marketing purposes when posting to social media.

They have https://www.example.com/folder/subfolder

For their marketing, they would like https://www.example.com/mysuperbuzzword which would point to the first URL but in the browser, you would still see the shorter URL.

My first thought was "I'll just add a rewrite rule in the .htaccess"

Something like Redirect 301 /mysuperbuzzword /folder/subfolder/ which would work but then the URL changes.

I did some reading and discovered the [P] flag. Then I tried this:

RewriteCond %{REQUEST_URI} ^/vanityurl RewriteRule ^(.*)$ /folder/subfolder [P]

The issue I have now is that because /vanityurl doesn't exist, instead of rewriting, I just get a 404 error.

I've been testing my rule using a .htaccess rule checking tool and the URL it spits out looks correct, but again, I just get a 404.

enter image description here

Also, if you use the flag [PT] the resource is found but the URL is changed in the address bar.

Upvotes: 0

Views: 90

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

You tested with a permanent redirect. Never do that. It is cached by the browser, and the browser will no longer do requests to the server. This is possible, because such a redirect is supposed to be... well... permanent. If you must test redirects, test them with a temporary redirect (302) and change them later if everything turns out to be fine.

With mod_rewrite you can do three things:

  • Do an internal rewrite. If you internally rewrite url a to url b, then the user sees url a, but url b is being executed on the server.
  • Do an external redirect. If you externally redirect url a to url b you send back a response: "Please request url b instead.". The browser then sends another request to the server with url b and changes the url in the address bar accordingly.
  • Do a proxy request. If you proxy url a to url b, the user requests url a. The server then opens a http connection and requests url b. It then waits for the response and channels that back to the client. It is very expensive to do such a thing via mod_rewrite.

What you simply want to do is:

RewriteRule ^vanityurl$ /folder/subfolder [L]

It as a simple internal rewrite.

Upvotes: 1

Related Questions