drq1257 2012-09-14 10:00 采纳率: 0%
浏览 31
已采纳

使用mod_rewrite模拟Facebook样式的URL

What I want the address bar to show:

http://facebook.com/user

http://facebook.com/user/ -> http://facebook.com/user

http://facebook.com/user/photos -> http://facebook.com/user/photos

My rewrite rules:

RewriteEngine On
RewriteRule ^(.+)/$ $1 [NC]
RewriteRule ^([A-Za-z0-9_-]+)/?([A-Za-z0-9_-]*)$ user.php?id=$1&second=$2 [NC,L]

What happens:

1). http://domain.com/user (working well)

2). http://domain.com/user/ (keeps the / in the address bar and destroys css/js/img paths)

3). http://domain.com/user/photos (same result as 2, correct except the paths)

If I use <base href="..."> to force the paths the page displays correctly. But I want to solve my problem without it.

How can I remove the trailing slash in the address bar? The rewriting seem to be working like intended.

  • 写回答

2条回答 默认 最新

  • doubi5127 2012-09-14 10:07
    关注

    When you are going to use Friendly URLs, you must use absolute paths for your resources.

    Initial Declaration

    You might have declared index.php with this way:

    <link rel="stylesheet" href="stylesheets/styles.css" />
    <img src="assets/user.png" />
    <script type="text/javascript" src="scripts/home.js"></script>
    

    Proposed Way using / for Absolute Paths

    But it has to be translated this way:

    <link rel="stylesheet" href="/stylesheets/styles.css" />
    <img src="/assets/user.png" />
    <script type="text/javascript" src="/scripts/home.js"></script>
    

    Notice the / in the front to make them as Absolute URLs.

    Using <base href="/" />

    If this is going to be a tedious task for you, you can use this tag:

    <base href="/" />
    

    This will make your Relative URLs to relate with the Root.

    Using a $baseurl variable

    Another better way is to prepend with a $baseurl variable.

    <link rel="stylesheet" href="<?php echo $baseurl; ?>/stylesheets/styles.css" />
    <img src="<?php echo $baseurl; ?>/assets/user.png" />
    <script type="text/javascript" src="<?php echo $baseurl; ?>/scripts/home.js"></script>
    

    This way, you can even change the $baseurl value if you are hosting in a folder and not in the root!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件