Вопрос

I'd like to do link shortening using PHP and Apache/.htaccess.

Here's how a link on my site looks:

https://mysite.com/item/this-is-a-book-on-toasters

Here's how I'd like the shortened link to look for the above link.

https://ms.co/Im8y2x

Currently, this is what I have in my .htaccess file:

RewriteCond %{HTTP_HOST} ^ms\.co$ [NC]
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ https://mysite.com/item/$1 [L,R=301]

So going to ms.co does redirect to mysite.com. My problem is that my PHP code at mysite.com/item has no knowledge of the 6 digit string (in this case, Im8y2x) so I can't query my database for the 6 digit string's matching URI (in this case, /this-is-a-book-on-toasters).

I know I need something added to my .htaccess Rewrite rules I'm just not sure what it is. Might someone be able to help?

Это было полезно?

Решение

I figured out my own question. If you just leave out R=301 then you'll preserve the URI (in this case, Im8y2x) and then you can access it with your scripting language (in my case, PHP) to redirect it to the full length URI.

So instead of this:

RewriteRule ^(.*)$ https://mysite.com/item/$1 [L,R=301]

do this:

RewriteRule ^(.*)$ https://mysite.com/item/$1 [L] 
// the only difference is the lack of ",R=301"

Другие советы

How about this?

RewriteCond %{HTTP_HOST} ^ms\.co/$1 [NC]
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ https://mysite.com/item/$1 [L,R=301]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top