RewriteRule works but ugly URL shows instead of pretty one

北战南征 提交于 2019-12-24 10:59:07

问题


This is my .htaccess file:

RewriteEngine on

RewriteBase /admin

RewriteRule menu/([0-9]+)/([0-9]+)/([a-z0-9]+) http://www.mysite.com/admin/index.php?m=$1&o=$2&token=$3 [R,L]

I had to include the full URL because without it, it kept redirecting to http://www.mysite.com/menu/1/1/login.php instead of mysite.com/admin/login.php

So I rewrote my links, so that they look like this:

<a href="/admin/menu/1/1/bl4h1234">Some link</a>

And that works fine, but the URL shows in the address bar as the ugly URL, but the whole purpose was to show the URL as the pretty URL :/

How can I fix that?


回答1:


An alternative (& standard [MVC / Front controller Patterns]) way to handle mod_rewrite rules and rewriting is to pass the whole url to your index.php and then process it there.

It actually makes it simpler in the long run, otherwise the complexity of your problems will only increase as you add more features.

As it seems you are using folders (menu|admin) with an index.php in each, you have no kind of router script. So you will need to handle the basic route in the .htaccess. You basically just need a rewrite for each folder.

The .htaccess goes in your root. Else you would need a rewrite for each folder and without the RewriteBase /path

Directory Structure (Where to put the .htaccess, in root):

ROOT>/
     /index.php
     /.htaccess
     /admin/
           /index.php
     /menu/
          /index.php
     /someOtherFolder/
                     /index.php
                     /somefile.php

The .htaccess rewrite

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^admin/menu/(.*)$ admin/index.php?route=$1 [L,QSA]
RewriteRule ^menu/(.*)$ index.php?route=$1 [L,QSA]

Then within your index.php files you handle the route, by exploding the $_GET['route'] param by /

<?php 
if(isset($_GET['route'])){
    $url = explode('/',$_GET['route']);
    //Assign your variables, or whatever you name them
    $m     = $url[0];
    $o     = $url[1];
    $token = $url[2];
}else{
    $m     = null;
    $o     = null;
    $token = null;
}
?>

Hope it helps.




回答2:


You are redirecting to the new URL via [R]. Instead, remove the protocol and domain from the rewrite and lose the [R]. This will perform an internal rewrite.

RewriteRule menu/([0-9]+)/([0-9]+)/([a-z0-9]+) index.php?m=$1&o=$2&token=$3 [L]



回答3:


  1. Don't create the rewrite to an absolute URL. Remove the protocol and the host name from the rewritten URL.
  2. Don't use the R flag if you don't want redirection.


来源:https://stackoverflow.com/questions/10372178/rewriterule-works-but-ugly-url-shows-instead-of-pretty-one

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