Mod Rewrite Slash Problem

北城余情 提交于 2019-12-23 05:36:11

问题


I searched this problem in the site, but I couldn't find a solution.

I have a php page, call http://www.domain.com/topic.php?name=xyz

I want to call this page with http://www.domain.com/topic/xyz

What I tried is;

RewriteEngine On

RewriteRule ^topic/([^/]*)$ /topic.php?name=$1 [L]

However because of this "/" I get 404 error. If I try "-" instead of "/" it works. I guess "/" forward user to folder "/topic" so I need a solution to fix it.


回答1:


The following should work given the fact that your topic name follows the pattern ([a-zA-Z0-9-_]+) - and if it doesn't match it, it probably should(and it's your job to sanitize it so that it matches), because it's a URL.

RewriteEngine On
RewriteRule ^topic/([a-zA-Z0-9-_]+).html$ topic.php?name=$1 [L]

NOTE:

In your request you say you want the url to look like this: http://www.domain.com/topic/xyz and in the .htaccess rule you tried to write it with .html at the end. If you don't want .html at the end you should do the following:

RewriteEngine On
RewriteRule ^topic/([a-zA-Z0-9-_]+)$ topic.php?name=$1 [L]



回答2:


I found my solution to problem. It is a bit late though :)

I edit my .htaccess such that

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule .* redirect.php [L] 

I create a redirect.php as you see. In this file, I explode slashes, then by using if statement I set

$path =  explode("/", $_SERVER['REQUEST_URI']);
switch ($path[1])
{
    case 'topic': $_GET[name]=$path[2]; include('topic.php'); break;
}

As you see setting $_GET as a code isn't handsome, but it works like a charm! :) Thanks all for your helps.




回答3:


Too bored to guess anymore.

My .htaccess (taken from your question):

RewriteEngine on
RewriteBase /
RewriteRule ^topic/([^/]*)$ /topic.php?name=$1 [L]

My topic.php:

<?php

var_dump($_GET);

Request:

http://localhost/topic/xyz

Result:

array(1) { ["name"]=> string(3) "xyz" }

So it just works on Apache 2.2.14




回答4:


I think you need to espace the forward slash, like so:

RewriteRule ^topic\/([^\/]*)$ topic.php?name=$1 [L]

And in Bogdan's solution you're missing a + after the character class, now it only matches one character :P




回答5:


If you have the line AddHandler type-map var in your httpd.conf, try commenting it out.

It might seem odd, but this functionality (which is not often used, but is enabled in the default httpd.conf for the Apache "It Worked!" page) has caused me grief along similar lines in the past.

It's something to do with the fact that you have a file "topic.php", and Apache allows you to call it like "topic/en-us". Or something like that. You'd have to look up the feature in the Apache docs to get the specifics; I'm just going off memory.



来源:https://stackoverflow.com/questions/5773648/mod-rewrite-slash-problem

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