Está en la página 1de 7

18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central

Conceptos (profitbricks-concepts.html) Características únicas (profitbricks-unique-features.html) Docker (setup-docker-on-ubuntu-at-profitbricks.html) CoreOS (setup-coreos-


cluster-on-profitbricks.html) Terraform (../tools/terraform/index.html) Go SDK (../libraries/go/index.html)

Inicie su centro de datos (https://www.ionos.com/pro/enterprise-cloud/signup/)

Tutoriales

Instalar y configurar mod_rewrite para Apache en CentOS 7


Creado por hitjethva (../users/profile/hitjethva.html) el 13 de mayo de 2016   apache (tags/Apache.html)
  18 comentarios (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#comments)

  Principiante

Tabla de contenido
Introducción (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#introduction)
Requisitos (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#requirements)
instalar apache (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#install-apache)
Habilitar módulo mod_rewrite (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#enable-mod_rewrite-module)
Habilitar archivo .htaccess (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#enable-.htaccess-file)
Configurar módulo de reescritura (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#configure-rewrite-module)
Redirigir www a no www (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#redirect-www-to-non-www)
Redirigir no www a www (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#redirect-non-www-to-www)
Redirigir todas las páginas del sitio web (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#redirect-all-website-pages)
Denegar acceso al tipo de archivo (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#deny-file-type-access)
Resumen (install-and-configure-mod_rewrite-for-apache-on-centos-7.html#summary)

ntroducción
pache se mod_rewrite puede usar para manipular URL. Se compila en el servidor web Apache base. Este módulo brinda la capacidad de manipular URL antes de determinar el
chivo apropiado o entregarlo a un script. Puede ayudarte si quieres ofrecer diferentes URL para el mismo archivo. Esto se usa más comúnmente cuando un visitante va a una
terminada dirección web, pero el servidor devuelve una página diferente. Este módulo utiliza un motor de reescritura basado en reglas para reescribir las URL solicitadas sobre la
archa. Admite un número ilimitado de reglas para proporcionar un mecanismo de manipulación de URL realmente flexible y potente. Puede ocultar información confidencial, como
denas de consulta, de las solicitudes de URL. Esto puede mejorar potencialmente la seguridad del sitio web.

n este tutorial, explicaremos cómo habilitar mod_rewrite y demostrar algunas formas comunes de usarlo en Apache en CentOS 7.

Requisitos
Un servidor que ejecuta CentOS 7

nstalar apache
ntes de comenzar con la mod_rewrite configuración del módulo, debemos instalar el servidor web Apache.

ara instalar Apache, ejecute el siguiente comando:

sudo yum install httpd -y

espués de instalar Apache, inicie el httpd servicio y habilítelo para que se inicie automáticamente al arrancar.

sto lo podemos hacer usando los siguientes comandos:

sudo systemctl start httpd.service


sudo systemctl enable httpd.service

continuación, debemos permitir el acceso al puerto predeterminado de Apache 80 (HTTP) usando firewalld .

sto lo podemos hacer ejecutando el siguiente comando:

sudo firewall-cmd --permanent --add-port=80/tcp

hora, vuelva a cargar el servicio de firewall para que los cambios surtan efecto.

sudo systemctl restart firewalld.service

https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 1/7
18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central

Habilitar módulo mod_rewrite


mod_rewrite módulo está habilitado de forma predeterminada en CentOS 7. Si encuentra que no está habilitado en su servidor, puede habilitarlo editando el 00-base.conf archivo
icado en el /etc/httpd/conf.modules.d/ directorio.

sudo nano /etc/httpd/conf.modules.d/00-base.conf

gregue o elimine el comentario de la siguiente línea:

LoadModule rewrite_module modules/mod_rewrite.so

uarde y cierre el archivo, luego reinicie el httpd servicio:

sudo systemctl restart httpd

Habilitar archivo .htaccess


na vez que se ha activado el mod_rewrite módulo, puede configurar sus reescrituras de URL creando un .htaccess archivo en su directorio raíz de documentos predeterminado. U
htaccess archivo nos permite modificar nuestras reglas de reescritura sin acceder a los archivos de configuración del servidor. Por esta razón, .htaccess es fundamental para su
rvidor web. Antes de comenzar, debemos permitir que Apache lea .htaccess los archivos ubicados en el /var/www/html directorio.

uedes hacer esto editando httpd.conf el archivo:

sudo nano /etc/httpd/conf/httpd.conf

usque la sección <directory /var/www/html> y cambie AllowOverride None a AllowOverride All

<Directory /var/www/html>
AllowOverride All
</Directory>

uardar y Salir.

hora reinicie Apache para que el cambio entre en vigor:

sudo systemctl restart httpd

Configurar módulo de reescritura


n esta sección, explicaremos la sintaxis básica de mod_rewrite y daremos algunos ejemplos.

uede escribir RewriteRules usando el siguiente formato:

RewriteRule pattern substitution [flags]

RewriteRule : Esta directiva especifica el nombre de la directiva mod_rewrite que desea utilizar.
Pattern : esta directiva especifica una expresión regular que coincide con la cadena deseada
Substitution : esta directiva especifica la ruta de la URL real de la página con la información que desea mostrar.
Flags : una bandera es una etiqueta al final de la directiva de regla de reescritura que especifica parámetros opcionales que pueden modificar la regla.

nalicemos RewriteRules con algunos ejemplos:

Redirigir www a no www


desea redirigir a los usuarios desde www un non-www dominio simple, deberá crear .htaccess un archivo en el directorio raíz de documentos de Apache.

ambie los directorios a la raíz de su documento:

cd /var/www/html

ea el .htaccess archivo:

sudo nano .htaccess

grega el siguiente contenido:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

uardar y salir del archivo.

odemos usar curl para probar que el www dominio redirige al non-www dominio:

https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 2/7
18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central

curl -I http://www.yourdomain.com

ebería ver el siguiente resultado:

HTTP/1.1 301 Moved Permanently


Date: Mon, 03 May 2016 18:20:53 GMT
Server: Apache/2.4.6 (CentOS)
Location: http://yourdomain.com/
Content-Type: text/html; charset=iso-8859-1

resultado anterior muestra la ubicación de redirección que no es www http://yourdomain.com/

Redirigir no www a www


desea redirigir a los usuarios de un non-www dominio simple a un www dominio, agregue el siguiente contenido a su .htaccess archivo:

sudo nano /var/www/html/.htaccess

grega el siguiente contenido:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

uardar y salir del archivo.

hora, use curl el comando para asegurarse de que el non-www dominio se redirige al www dominio:

curl -I http://yourdomain.com

ebería ver el siguiente resultado:

HTTP/1.1 301 Moved Permanently


Date: Mon, 03 May 2016 18:20:53 GMT
Server: Apache/2.4.6 (CentOS)
Location: http://www.yourdomain.com/
Content-Type: text/html; charset=iso-8859-1

bove output shows the www redirect location http://www.yourdomain.com/

Redirect All Website Pages


you want to redirect all pages from "olddomain.com" to "newdomain.com", edit the .htaccess file:

sudo nano /var/www/html/.htaccess

dd the following content:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.olddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^olddomain.com$
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

ave and exit the file.

ow, use curl to test that the "www.olddomain.com" domain redirects to the "www.newdomain.com" domain:

curl -I http://www.olddomain.com

ou should get a 301 Moved Permanently response that shows you the new domain redirect location.

Deny File Type Access


you want to deny users to access specific file types such as: .pdf , .css , .gif , .png , or .bmp then edit your .htacces file:

sudo nano /var/www/html/.htaccess

dd the following content:

RewriteEngine on
RewriteRule .*\.(pdf|css|gif|png|bmp)$ - [F,NC]

ave and exit the file.

https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 3/7
18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central

Summary
hose are just a few examples of how mod_rewrite can be used. If you have questions about these examples please let us know below. You are also welcome to post in the
ofitBricks DevOps Community (https://devops.profitbricks.com/community) section of this site.
  SHARE
scribe (https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7subscribe/)

author: Jethva
Hitesh Jethva (../users/profile/hitjethva.html)
May 13, 2016
 Apache (tags/Apache.html)

Related Tutorials
Popular Tutorials

anshul.go87 (../users/profile/anshul.go87/index.html) on Nov 12, 2016 commented,


I want to redirect social media crawlers to a separate snapshot page using the VirtualHost. This is how I have written the virtual host:

NameVirtualHost *:80

<virtualhost *:80="">

ServerName www.mysite.com DocumentRoot /var/www/html/

<directory var="" www="" html=""/> Allow From All RewriteEngine On RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit/[0-9]|Twitterbot|Pinterest|Google.*snippet)
RewriteRule . http://www.mysite.com/snapshot [L] </directory>

</virtualhost>

After using this virtual host rule, social media crawling is working fine, but the site stops working, it gives index page not found error.

Please help me to write a correct virtual host.

dimon28.05 (../users/profile/dimon28.05/index.html) on Apr 28, 2017 commented,


Thanks!!! Good luck ))))

sweetheart (../users/profile/sweetheart.html) on May 11, 2017 commented,


Need help with Apache start error. I can not start it after my failed attempt to install ISPConfig3 on Centos7. I uninstalled and reinstalled apache; but it is giving the same
error message. I do not see any syntax error in line 353. Thanks a lot for the help.

[root@test1 mnasimul]# systemctl status -l httpd

● httpd.service - The Apache HTTP Server

Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)

Active: failed (Result: exit-code) since Thu 2017-05-11 15:31:55 EDT; 14min ago

Docs: man:httpd(8)

man:apachectl(8)

Process: 3695 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)

Process: 3685 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited,

status=1/FAILURE)

Main PID: 3685 (code=exited, status=1/FAILURE)

May 11 15:31:55 test1.nasim.com systemd[1]: Starting The Apache HTTP Server...

May 11 15:31:55 test1.nasim.com httpd[3685]: httpd: Syntax error on line 353 of

/etc/httpd/conf/httpd.conf: Syntax error on line 1 of /etc/httpd/conf.d/suphp.conf: Cannot load

modules/mod_suphp.so into server: /etc/httpd/modules/mod_suphp.so: cannot open shared object file:

No such file or directory


https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 4/7
18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central
No such file or directory
May 11 15:31:55 test1.nasim.com systemd[1]: httpd.service: main process exited, code=exited,

status=1/FAILURE

May 11 15:31:55 test1.nasim.com kill[3695]: kill: cannot find process ""

May 11 15:31:55 test1.nasim.com systemd[1]: httpd.service: control process exited, code=exited

status=1

May 11 15:31:55 test1.nasim.com systemd[1]: Failed to start The Apache HTTP Server.

May 11 15:31:55 test1.nasim.com systemd[1]: Unit httpd.service entered failed state.

May 11 15:31:55 test1.nasim.com systemd[1]: httpd.service failed.

kostyanius (../users/profile/kostyanius/index.html) on Mar 05, 2018 commented,


Redirect from one site to another does not work at all. should i install mod_rewrite module for this or only enough to add entry LoadModule rewrite_module
modules/mod_rewrite.so for this?

nitaamba234 (../users/profile/nitaamba234/index.html) on Oct 03, 2018 commented,


I can not start it after my failed attempt to install ISPConfig3 on Centos7. I uninstalled and reinstalled apache; but it is giving the same error message. I do not see any
syntax error in line 353. Thanks a lot for the help. and for the help you can visit Epson error code 0x97 (https://printertechsupportnumbers.com/blog/fix-epson-wf-3620-error-
code-0x97/) and get the solution

JackWill13 (../users/profile/JackWill13/index.html) on Oct 15, 2018 commented,


We are one stop solution for your printer issue. Make a call on 1-877-916-7666

Assistance for all is an amazing and one of the biggest printer support service providers in the USA. Our customer-centric process helps us to understand the specific
requirements of our clients and helps us to come to the best possible conclusion for them.

We are also knom for offering printer driver support services which are crafted under the aegis of the expert professionals. More Website -
https://www.assistanceforall.com/services/printer-support/

JackWill13 (../users/profile/JackWill13/index.html) on Oct 15, 2018 commented,


Are you looking for a printer support service (https://www.assistanceforall.com/services/printer-support/)? Call us at 1-877-916-7666

Printers in the present era become an integral part of our day to day life. From offices to home, printers have made their places according to their needs, requirements, and
sizes.

Ronal (../users/profile/Ronal/index.html) on Oct 17, 2018 commented,


To work more on this topic, I suggest you to look at https://www.topamericanwriters.com/essayontime-com-review/ (https://topamericanwriters.com/essayontime-com-
review/) because it's the exactly the same thing. It will help you like it helped me a lot. Thank you once again.

ghejf1392 (../users/profile/ghejf1392/index.html) on Oct 18, 2018 commented,


This module provides the ability to manipulate URLs prior to determining the appropriate file or handing off to a script.

If anyone faces Brother Printer issue or any other printer issue get help from this Brother Printer Support (https://www.brotherprintersupportnumber.com/brother-customer-
support/)

ethan.john2019 (../users/profile/ethan.john2019/index.html) on Nov 01, 2018 commented,


This is most commonly used when a visitor goes to a certain web address, but the server returns a different page. If anyone face printer error gets help from this printer not
activated error code 20 (https://www.hpsupporthelpline.com/blog/tag/printer-not-activated-error-code-20/)

markcruz (../users/profile/markcruz/index.html) on Nov 02, 2018 commented,


If you are stuck anywhere or finding it difficult to find a way out, you can talk to Brother Printer Tech Support Number and get instant help regarding the installation of printer
drivers on your system.

https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 5/7
18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central

markcruz (../users/profile/markcruz/index.html) on Nov 02, 2018 commented,


How to Install Brother Printer Setup?

When you decide to install the printer driver with the help of USB or Parallel cable, you might face problems in the installation of original brother printer driver. The built-in
driver of windows might have been installed. As you know, the built-in drivers provide support only for the fundamental functioning of the brother systems; it is recommended
to use the brother original printer driver instead. You can contact on Brother Printer Support Number (http://www.printer-customer-number.com/brother-printer-support.html)
to get immediate help regarding the installation of printer drivers on your system

markcruz (../users/profile/markcruz/index.html) on Nov 02, 2018 commented,


If you are stuck anywhere or finding it difficult to find a way out, you can talk to Brother Printer Tech Support Number (http://www.brotherprintercustomerservice.com/) and
get instant help regarding the installation of printer drivers on your system.

dhed1392 (../users/profile/dhed1392/index.html) on Nov 02, 2018 commented,


Look for the solutions only after you have identified the actual reason for this error to occur in your system. For resolve any type of issue then visit:

https://www.hptechnicalsupportphonenumbersusa.com/blog/hp-printer-in-error-state/

hfjkd1392 (../users/profile/hfjkd1392/index.html) on Nov 05, 2018 commented,


With the goal for this to work, a printer driver must be introduced on the Terminal Server that matches the driver introduced on the nearby PC. This is risky since you can't
simply make sure which printer is introduced on associating PCs. View Epson Error Code 0xf1 (https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-
apache-on-centos-7/%E2%80%9Dhttps://www.printererrorrepair.com/blog/how-to-fix-epson-printer-error-code-0xf1/%E2%80%9D) to tackle problems of printer.

happywheelsgame (../users/profile/happywheelsgame/index.html) on Nov 08, 2018 commented,


He just lives as if he never died. Just enjoy it, rest ... it begs to be bet like game: happy wheels (http://happy-wheelsgames.com) basketball legends game (http://happy-
wheelsgames.com/basketball-legends-game)

anuragsinga6256 (../users/profile/anuragsinga6256/index.html) on Nov 10, 2018 commented,


Hey! I can set up my URL rewrites by creating an .htaccess file in your default document root directory. A .htaccess file allows us to modify our rewrite rules without
accessing server configuration files. If anyone having issues regarding to canon printer offline (http://printertechsupportnumbers.com/blog/how-to-fix-canon-printer-offline-
error/) just follow this link.

alishiasergi (../users/profile/alishiasergi/index.html) on Nov 10, 2018 commented,


A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.
happy wedding anniversary wishes (https://www.weddinganniversarywishesmessages.com/2017/03/anniversary-wishes-for-couple-with-heart-touching-messages-and-
images.html)

Log In, Add a Comment (../users/login/index.html%3Fnext=%252Ftutorials%252Finstall-and-configure-mod_rewrite-for-apache-on-centos-

(../index.html)

https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 6/7
18/4/23, 16:30 Install and Configure mod_rewrite for Apache on CentOS 7 | IONOS DevOps Central

https://devops.ionos.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7.html 7/7

También podría gustarte