Search code examples
phpapachehttp-redirectweb-applicationshttp-headers

Accessing file in parent directory of folder containing index file


The directory is like so: htdocs

  • public

    • index.php
  • welcome.php

The 'public' folder is set as the document root, so that incoming requests go to index.php. The index.php checks to see if the user is authenticated, and if not it has a redirect to send them to the welcome page.

header("Location: welcome.php");

However, I keep getting a 404 error, despite the URL displaying the correct file path.

Any thoughts? Here's what I've tried.

header("Location: /welcome.php");
header("Location: ./welcome.php");
header("Location: ../welcome.php");

.htaccess

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

^The above created too many redirects.

Placing the index.php file in the same folder as welcome.php works fine but I'm trying to organize my web app and can't do that if I have to keep everything at or below the index.php file.


Solution

  • Seems like you are using Apache as your webserver. What you are trying to do is not possible. If the document root for your web application in Apache is set to the directory public/ then you will only be able to serve files from within that directory. Since welcome.php is at the same level as public/ and not within, you cannot serve that file and Apache is correctly serving you a 404 error.

    Instead, consider restructuring your approach to

    - public/ (foo.com)
    -- index.php
    -- secure/
    --- index.php
    -- welcome.php
    

    When a user lands on foo.com ask them to login, once they log in redirect them to foo.com/secure/index.php. If someone tries to access foo.com/secure/index.php and they are not authenticated, header them back to the welcome.php or index.php using header("Location: ../welcome.php");