Search code examples
apache.htaccesscodeigniter

Is there any way to simplify my url with .htaccess?


I am trying to simplify my url using .htaccess RewriteRule but I am not succeeded in it.

I want the url from this http://localhost/site/auth to be like this http://localhost/auth,I want to remove the site from the url.

What I tried so far

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite --- http://localhost/site/auth => http://localhost/auth
RewriteRule ^site/auth$ /auth?&%{QUERY_STRING}
</IfModule>

Solution

  • You need to code the rule the other way round. You want to internally rewrite incoming requests, so requests to http://localhost/auth ...

    RewriteEngine On
    Rewrite ^/?auth$ => /site/auth [END]
    

    That's all.

    No need to test for existing files or folders here, since you do not implement a generic rule, but a specific one. And no need to add the query string, that is the default for rewriting anyway. Also I fail to see the benefit of the <IfModule ...> brackets, since your logic won't work without that module anyway:

    For this to work the apache http server's rewriting module needs to be loaded into the server and it needs to be activated for the http host "localhost" which most likely simply is the default host in your case.

    In case you also want to add the external redirection this would do:

    RewriteEngine On
    RewriteRule ^/?site/auth$ /auth [R=301,END]
    Rewrite ^/?auth$ => /site/auth [END]
    

    You probably want to start out using a R=302 temporary redirection first and only change that to a R=301 permanent redirection later, once you are sure everything works as expected. That way you prevent caching issues.


    It makes sense to implement such rule in the actual host configuration of your http server. If you prefer to use distributed configuration files instead (".htaccess"), for example because you plan to deploy to a cheap host provider later where do you not have access to the actual configuration, then you need to make sure the interpretation of such files is enabled for that location (see the AllowOverride directive in the documentation). And you need to accept a performance penalty in that case.