You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移至Nginx后无法访问CodeIgniter控制器的问题求助

解决CodeIgniter从Apache迁移到Nginx后的POST请求问题

你的问题根源在于Nginx配置未正确处理/directory目录下的CodeIgniter单入口路由,导致请求没有被转发到/var/www/directory/index.php,CodeIgniter无法解析目标控制器,最终返回HTML页面(大概率是默认首页或404页面)。

步骤1:修改Nginx配置

更新/etc/nginx/conf.d/default.conf,添加针对/directory的专属路由规则,确保所有该目录下的请求都正确转发到CodeIgniter的单入口文件:

server {
    listen       80;
    server_name  localhost;
    root /var/www;
    #access_log  /var/log/nginx/host.access.log  main;

    # 处理/directory下的CodeIgniter请求
    location /directory {
        index index.php;
        # 尝试直接访问文件/目录,否则转发到index.php并携带查询参数
        try_files $uri $uri/ /directory/index.php?$query_string;

        location ~ \.php$ {
            fastcgi_pass   unix:/var/run/php/php7.4-fpm.sock;
            include        fastcgi_params;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            # 确保CodeIgniter能正确获取路由参数
            fastcgi_param  REQUEST_URI      $request_uri;
        }
    }

    location / {
        index index.html index.htm index.php;
        try_files $uri $uri/ /index.php;
        location ~ /.ssh {
            deny all;
            return 403;
        }
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root /var/www;
    }

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

    location ~ /\.ht {
        deny  all;
    }
}

步骤2:检查CodeIgniter配置

打开/var/www/directory/application/config/config.php,确认以下配置项:

  • 设置正确的基础URL:
    $config['base_url'] = 'http://SERVER_IP/directory/'; // 替换为你的服务器IP或域名
    
  • 配置适合Nginx的URI协议:
    $config['uri_protocol'] = 'REQUEST_URI';
    

步骤3:测试验证

  1. 重新加载Nginx配置使修改生效:
    sudo nginx -s reload
    
  2. 使用原curl命令重新测试:
    curl --request POST \
      --url http://SERVER_IP/directory/index.php/NameOfController \
      --header 'content-type: application/x-www-form-urlencoded' \
      --data token=xxx \
      --data user_id=1234 \
      --data trx_number=123456789 \
      --data trx_value=1000000
    

此时应该能收到预期的JSON响应。

内容的提问来源于stack exchange,提问作者Liso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:15:52