【问题标题】:apache mod_rewrite to hide index.php but change rest of php files to directoriesapache mod_rewrite 隐藏 index.php 但将其余 php 文件更改为目录
【发布时间】:2016-12-15 19:48:17
【问题描述】:

好吧,标题几乎概括了它。我正在尝试隐藏 index.php,但任何其他 php 文件(例如 file.php)都会变成 /file/ 等...

到目前为止,我有这个 htaccess,但它不工作......

Options -Indexes -Multiviews

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

谁能帮我解决这个问题?

谢谢。

【问题讨论】:

    标签: php apache .htaccess mod-rewrite


    【解决方案1】:

    隐藏index.php 的最佳方法是永远不要链接到它,这不是必需的,我不知道人们为什么这样做。使用href 中的/ 链接到Web 根目录,或使用./ 链接到当前目录。

    # 404.php file should set status with header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
    ErrorDocument 404 /404.php
    Options -Indexes -Multiviews
    RewriteEngine On
    RewriteBase /
    # remove .php from legitimate requests (you should still update all the URLs served so that normal crawling/browsing doesn't 301 on every link)
    RewriteCond %{THE_REQUEST} ^\S++\s++((/[^?\s]+?)??/index\.php)(\?\S*+)?\s [OR]
    RewriteCond %{THE_REQUEST} ^\S++\s++((/[^?\s]+?)\.php)(\?\S*+)?\s
    RewriteCond %{DOCUMENT_ROOT}%1 -f
    RewriteRule ^ %2/%3 [NS,NE,L,R=301]
    # add trailing / to legitimate requests missing it
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule .+ $0/ [NS,NE,L,R=301]
    # rewrite all requests that look like directories to files, /foo/ to /foo.php and /bar/baz/qux/ to /bar/baz/qux.php
    RewriteCond %{DOCUMENT_ROOT}$1.php -f
    RewriteRule ^([^./][^/]*+(?:/[^./][^/]*+)*)/$ $1.php [NS,L,DPI]
    # allow everything else to be processed as normal file request or 404
    

    【讨论】:

    • 我想你误解了我的问题。您写了“将所有看起来像目录的请求写入文件”,但我需要将 php 文件更改为目录,而不是将目录更改为 php 文件。另外隐藏 index.php 我的意思更多的是,如果用户键入 index.php,它会自动返回 / 并且不显示 php。
    • 所以php文件已经不存在了,现在文件夹呢?或者实际文件类似于/bar/baz/qux.php,而您希望出现的URL为/bar/baz/qux/
    • 我认为您误解了我的解决方案。您从未说过您想要外部重定向,只是您希望 /file/ 解析为 file.php,这是通过内部重写完成的。
    • 不,我希望 file.php 变成 /file/ 而 index.php 变成 /。如果有人将地址写成 file.php,它会自动转移到 /file/ 等等...
    • @FoxyFish 你太忘恩负义了吧? Didn't answer my question 也不注意我编辑答案。如果您不希望 /foo/ 在内部重写为 foo.php,请省略最后一条规则 + 条件。也许我应该删除我的答案并停止试图帮助你?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2012-07-03
    • 2015-03-18
    • 1970-01-01
    • 2016-12-21
    相关资源
    最近更新 更多