iT邦幫忙

0

RewriteRule寫法求助(含中文)

各位前輩大家好
最近我在把php網站的網址做urL rewrite
但在包含中文的時候遇到一些問題
希望可以幫我解惑

原本:index.php?cat1=首頁
要變成:首頁

這樣寫的話會抓不到(英數沒問題)

RewriteRule ^(\w*)$ index.php?cat1=$1 

這樣也是(英數也不行)

RewriteRule ^(.*)$ index.php?cat1=$1 

這樣寫的話則可以,所以想說應該不是編碼的問題(?)

RewriteRule ^([首頁]*)$ index.php?cat1=$1 

想請問要如何達成可以接收任意中文字的功能?
謝謝~

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

6
weiclin
iT邦高手 4 級 ‧ 2015-08-05 23:51:55
最佳解答

你應該每次 $_GET['cat1'] 都抓到 index.php 吧?
rewrite 的行為, 是改寫後會再比對一次
所以 xxx.com/中文 被改寫成 xxx.com/index.php?cat1=中文
然後 xxx.com/index.php?cat1=中文 又被改寫成 xxx.com/index.php?cat1=index.php
最後 rewrite 發現改寫前後都是 index.php 就停了

你可以試試看這樣弄, 要 apache 2.3.9 以後才支援, 但現在應該都用 2.4 了:

<pre class="c" name="code">RewriteRule ^(.*)$ index.php?cat1=$1 [END]
看更多先前的回應...收起先前的回應...
weiclin iT邦高手 4 級 ‧ 2015-08-05 23:57:44 檢舉

如果 END 不能用, 那你就只好先加上 RewriteCond 排除掉有 index.php 的情況

<pre class="c" name="code">
RewriteCond "%{REQUEST_URI}"  !^/index.php
RewriteRule ^(.*)$ index.php?cat1=$1
catding iT邦新手 5 級 ‧ 2015-08-06 00:39:52 檢舉

用了以後
500Internal Server Error

catding iT邦新手 5 級 ‧ 2015-08-06 00:43:03 檢舉

RewriteCond "%{REQUEST_URI}" !^/index.php

這樣以後不會500了
但依然抓不到資料

weiclin iT邦高手 4 級 ‧ 2015-08-06 00:54:06 檢舉

你是寫在 .htaccess 裡面嗎?
沒抓到資料, 那 echo $_GET['cat1'] 顯示什麼?

catding iT邦新手 5 級 ‧ 2015-08-06 00:54:12 檢舉

好像不是這方便的問題
因為英數就可以

catding iT邦新手 5 級 ‧ 2015-08-06 00:55:22 檢舉

方便X
方面O
一直打錯字.....

weiclin iT邦高手 4 級 ‧ 2015-08-06 00:58:19 檢舉

你把你現在的設定完整的貼上來吧

catding iT邦新手 5 級 ‧ 2015-08-06 01:04:24 檢舉

.htaccess的部分

<pre class="c" name="code">
RewriteEngine On
RewriteRule ^css($|/) - [L,NC]
RewriteCond "%{REQUEST_URI}"  !^/index.php  
RewriteRule ^(.*)$ index.php?cat1=$1

打中英數
echo出來都是index.php

如果把(.*)換成(\w*)
英數正常
中文會502 Bad Gateway

weiclin iT邦高手 4 級 ‧ 2015-08-06 01:04:30 檢舉

RewriteRule ^(\w*)$

你有把你這行改成跟我的一樣嗎?
\w 相當於 [a-zA-Z0-9], 沒辦法拿來比對中文喔

catding iT邦新手 5 級 ‧ 2015-08-06 01:06:44 檢舉
<pre class="c" name="code">RewriteRule ^(.*)$ index.php?cat1=$1  

打中英數
echo出來都是index.php

weiclin iT邦高手 4 級 ‧ 2015-08-06 01:09:50 檢舉

那現在問題就是為什麼 RewriteCond 似乎沒起作用了
改成這樣呢?

<pre class="c" name="code">
RewriteEngine On
RewriteRule ^css($|/) - [L,NC]
RewriteCond "%{REQUEST_URI}"  !index.php
RewriteRule ^(.*)$ index.php?cat1=$1
weiclin iT邦高手 4 級 ‧ 2015-08-06 01:15:50 檢舉

再不行的話, 換個思考方式, 不存在的檔案才 rewrite

<pre class="c" name="code">
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?cat1=$1
catding iT邦新手 5 級 ‧ 2015-08-06 01:19:15 檢舉

可以了!!
謝謝你半夜還幫我回答問題

學到一課了
現在回去看,發現自己幹了不少蠢事.....

2
老鷹(eagle)
iT邦高手 1 級 ‧ 2015-08-05 21:52:08

這篇可以參考一下,希望有幫助到您~!

catding iT邦新手 5 級 ‧ 2015-08-05 22:42:11 檢舉

有看過這篇了
但是(.*)不知道為什麼依然抓不到QQ
謝謝你~

我要發表回答

立即登入回答