大网数据广告活动
服务器运维问答

mod_rewrite and PATH_INFO with php project

· 52CE 我爱测

I have a project that reads the $_SERVER['PATH_INFO'] variable when loading pages, therefore it reads pages in the format of http://address/index.php/pagename and I would like to use mod_rewrite to remove the index.php part of th…

问题原文

原帖链接 · markzz · CC BY-SA 3.0

I have a project that reads the $_SERVER['PATH_INFO'] variable when loading pages, therefore it reads pages in the format of http://address/index.php/pagename and I would like to use mod_rewrite to remove the index.php part of the url and make the previous URL http://address/pagename. If one visits http://address/pagename, it needs to load the page as if that person visited http://address/index.php/pagename.

With Nginx, the following configuration works and does the rewrite...

server {
    listen       80;
    server_name  localhost;

    root   /srv/http/web/html;
    index  index.php;

    location ~ ^/[^/]+\.php($|/) {
        fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_split_path_info ^(/[^/]+\.php)(/.*)$;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  PATH_INFO        $fastcgi_path_info;
        include        fastcgi_params;
    }

    location ~ .* {
        rewrite ^/(.*)$ /index.php/$1 last;
    }
}

How would I accomplish this in apache. I currently have it working so that the root displays correctly and writing urls with the index.php part works. How can I make the rewrite rule work and still be able to use the $_SERVER['PATH_INFO'] variable? What could I put in the .htaccess to make it work?

已采纳解答

原帖链接 · Anubioz · CC BY-SA 4.0

You cannot directly change $_SERVER["PATH_INFO"] variable from within apache when php is compiled like a module.

But here's a workaround that will do the job just fine:

  1. Create a rewrite_pathinfo.php file with the following contents:

    <?php
    if (!empty($_SERVER['PATH_INFO'])) header("Location: " . $_SERVER['PATH_INFO']);
    $_SERVER['PATH_INFO'] = $_SERVER['REDIRECT_ORIGINAL_PATH'];
    ?>
    
  2. Put this into your .htaccess:

    php_value auto_prepend_file "/var/www/vhosts/path_to_your/rewrite_pathinfo.php"
    
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) /index.php [QSA,L,PT,E=ORIGINAL_PATH:/$1]
    

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-03-30)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。