문제

This is my first question:

I have created a URL Shortner Service in PHP.It works completely without any problem but there was a problem:

Someone who wants to access his url should type : MyDomain.com/go.php?u=key Here i tried to remove .php extention by configuring apache and worked.Now it is like that: MyDomain.com/go?u=key

but some services such TinyUrl.com works like that: TinyURL.com/key !!!!

How can i get this in php?

thanks a lot.

도움이 되었습니까?

해결책

You basicly use mod_rewrite.

With mod_rewrite you can say that all requests which are like

www.example.com/[A-Za-z1-9]

are redirected to:

www.example.com/shorturl.php?key=$1

While $1 is the extracted variable from the requested URL.

There is no proper way to do it with pure PHP.

The rewrite rule could look like this:

RewriteRule ^([A-Za-z1-9]*)$ shorturl.php?key=$1 [L]

I would exclude files which really exists from the rewriting, use for this RewriteCond.

This could be done like here:

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
# If the request is not for a valid link
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([A-Za-z1-9]*)$ shorturl.php?key=$1 [L]

(Source: anubhava at RewriteCond to skip rule if file or directory exists)

다른 팁

create .htaccess file to redirect any request to your domain to one file lets say go.php

so in .htacess do like this:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ go.php?key=$1 [PT,L]

</IfModule>

This redirection any request like mydomain.com/userkey to mydomain.com/go.php?key=userkey

now in your index.php you can do your redirection login.

<?php 

$key = $_GET['key'];

// your logic here. 

?>

This ref will solve your problem.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)/?$ redirect.php?c=$1 [L] 
</IfModule>

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top