htaccess get code and redirect with php

无人久伴 提交于 2019-12-25 12:15:15

问题


Ex:

If we entered these url (Like This site)

http://stackoverflow.com/questions/10139779/ or http://stackoverflow.com/questions/10139779

Its automatically redirect to this url http://stackoverflow.com/questions/10139779/handling-get-with-htaccess

I want to get this code (10139779) from url and redirect to full url. Someone go to full url how to get this code (10139779)

Edit :

I created htaccess file like this.

<Files .htaccess>
order allow,deny
</Files>

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^(\w+)$ ./load.php?code=$1

Now i want to give video title to url after video id Like this www.example.com/16056/video-title

load.php

<?php
echo $_GET['code'];

//I can get video title from php then how to give to url it?
?>

I can get code this from www.example.com/16566 but i can't get code this from this url www.example.com/16566/video-title

after id / link was doesnt work. how to fixed it


回答1:


Send out a location header for the correct URL. (load.php:)

<?php
    header('Location: /videos/'.$_GET['code'].'/'.getTheVideoTitle($_GET['code']));
?>

There is nothing you can do in .htaccess to get the video title, so php must do it.

Also, for .htaccess:

RewriteRule ^(\w+)$ ./load.php?code=$1

Should be:

RewriteRule ^(\w+)/*$ ./load.php?code=$1

This makes it match slash(s) after the URL. If you also want it to match the title after the URL, make it:

RewriteRule ^(\w+) ./load.php?code=$1



回答2:


This answer is an additional update of @bjb568's answer, which handles exceptions.

<?php
if(isset($_GET['code'])) {
  $code = (int)$_GET['code'];
  $url = '/videos/' . $code . '/' .getTheVideoTitle($code);
} else {
  $url = '404_page_not_found.php'; // or redirect visitors to homepage
}
header("Location: $url");
exit;
?>

Also, this prevents someone intentionally "hack" the link by entering strings with escape character & crash the code. (Of course, it's developer's duty to validate the input in the getTheVideoTitle() function)



来源:https://stackoverflow.com/questions/22888986/htaccess-get-code-and-redirect-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!