php – Redirection using mod_rewrite

Question: Question:

【Thing you want to do】

Redirect access to a specific URL to a fixed file


Assuming there was access to sunday.local / app / get / 1

Redirect to sunday.local / dispatch.php.

I want to parse app / get / 1 in dispatch.php and call it in the internal format (dispatch), but the redirect does not work as expected.


  • OS: Ubuntu14.04
  • Apache: 2.4.7


  1. Create VirtualHost settings /etc/apache2/sites-available/sunday.local.conf

AllowOverride All allows the use of .htaccess.

    <VirsualHost *:80>
    ServerName sunday.local
    DocumentRoot /home/oono/bear/public
    ErrorLog /var/log/apache2/
    CustomLog /var/log/apache2/ combined
    LogLevel warn
    <Directory "/home/oono/bear/public">
        Require all granted
        AllowOverride All

  1. Enable VirtualHost

Run the following command to enable

    $ sudo a2ensite sunday.local
    $ sudo service apache2 reload
  1. Added to / etc / hosts

I added the following.   sunday.local

Place /home/oono/bear/public/test.html

Access http://sunday.local/test.html from your browser and check that it is displayed.

  1. Enable mod_rewrite

Enable Apaceh module rewrite

    $ sudo a2enmod rewrite
    $ sudo service apache2 restart
  1. Create .htaccess

Create .htaccess in the document root "/home/oono/bear/public" of sunday.local Refer to

    RewriteEngine on
    RewriteRule ^/$ [R=302,L]
  1. Access from a browser

First of all, since it is a test, I expect that if you access "sunday.local /" in an easy-to-understand manner, you will be redirected to "", but the screen will be 403 Forbidden.

Is something missing or wrong?

Answer: Answer:

When using rewrite with .htaccess, the relative path from the installed path is entered.

http://sunday.local   =>  ""
http://sunday.local/  =>  ""  【注:最初の / は含まれません。】
http://sunday.local/test.html  =>  "test.html"

Therefore, it does not match the RewriteRule regular expression ^ / $ and does not behave as expected.
If there is no argument, it will be written as ^ $, and if there is an argument, it will be written as ^ (. *) $.

For example, try the following .htaccess.

RewriteEngine on
RewriteRule ^$ [R=302,L]
RewriteRule ^(.*)$$1 [R=302,L,NE]
Scroll to Top