doujing5937 2015-02-16 22:43
浏览 45
已采纳

尝试使用.htaccess缩短URL,但遇到配置错误

Brief intro: I'm attempting to set up a short URL system using a database and php. I've however came across a much shorter/quicker approach using a .htaccess file, regex, and a local config file. This tutorial however doesn't offer much support or explanation, and it's the first instance of URL re-writing I've seen.

Here's the code for the php script that gets the arguments passed into the page:

<?php

$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links))
{
    header('Location: ' . $links[$_GET['l']]);
}
else
{
    header('HTTP/1.0 404 Not Found');
    echo 'Unknown link.';
}

?>

So in other words it checks to see if the argument passed is in the static config file (example here would be google: http://example.com/index.php?l=google), and if so, then of course re-directs them to the site. Configuration file contents:

google  = https://www.google.com/
fb      = https://www.facebook.com/

Fairly logical. Can understand how it works. My problem however comes with the .htaccess file as mentioned above. I've only dabbled with regex, and plan to learn more. However currently I'm not skilled enough to really understand the syntax required to write what is needing to be achieved. What needs to happen is for the user to basically type in www.example.com/url/google and for them to be re-directed to www.example.com/url/index.php?l=google - this is something I've been unable to get to work, and I just receive web server config errors. Config file for .htaccess:

RewriteEngine On

RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]

Can anyone advise on the cause of the issue? Sorry for the lack of understanding on the regex part. I'm trying to skill up on it. I'd just like to get the fix in place so I can continue on my project, as it's only a small part of it.

Thanks a lot.

  • 写回答

1条回答 默认 最新

  • douceng7070 2015-02-16 23:17
    关注

    This will redirect it:

    RewriteEngine On
    
    RewriteCond %{REQUEST_URI} ^/url/([a-z]+)$ [NC]
    RewriteRule ^ /url/index.php?l=%1 [R=301,L]
    
    RewriteCond $1 !^(index\.php)
    RewriteRule ^(.*)$ index.php?l=$1 [L]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况