Home .htaccess rewriting URLs that don't exist
Reply: 1

.htaccess rewriting URLs that don't exist

Jesse Orange
1#
Jesse Orange Published in 2017-12-04 15:42:55Z

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.

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

Sumurai8
2#
Sumurai8 Reply to 2017-12-04 19:49:17Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301147 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO